我正在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