我正在C++ CLI中开发基于托盘图标的应用程序。我正在使用Mutex来确保一次运行我的应用程序的单个实例。但是每次启动新实例时,当前实例的窗口都应该激活。 我正在使用PostMessage(Pinvoke)向窗口发送消息。但经过3或4次连续运行后,我的应用程序崩溃。使用Mutex的C++/CLI中的单实例应用程序
任何想法为什么会发生。请帮忙!!
我已经写在main()函数的代码,
Mutex ^mutex = gcnew Mutex(true, "{8F6F0AC4-B9A1-45fd-A8CF-72F04E6BDE8F}");
if (mutex->WaitOne(TimeSpan::Zero, true))
{
// New Instance. Proceed......................
}
else// An instance is already running. Activate it and return
{
// send our Win32 message to make the currently running instance
// jump on top of all the other windows
try
{
HWND hWindow = FindWindow(nullptr, "MyWindow");
if(hWindow)
PostMessage(hWindow, WM_ACTIVATE_APP, nullptr,nullptr);
}
catch(Exception^ Ex)
{
}
return -1;
}
感谢&问候,
罗希尼
添加一些代码可以帮助。 – 2014-09-11 09:59:04
嗨@AntonSavin Savin,我添加了代码 – 2014-09-11 10:11:21
嗯,你在说谎,告诉应用程序它已被激活,但并未实际激活它。这样的谎言有烙在你脸上的烙印。您必须改用SetForegroundWindow()。避免重新发明轮子,这在.NET中已经得到很好的支持。使用WindowsFormsApplicationBase类,IsSingleInstance属性和StartupNextInstance事件。 – 2014-09-11 10:23:24