I must forbid the running of another instance of my app if itsd already running. I tried if (hInstance == hPrevInstance) but that obviously didnt work.
How can this be achieved?
Thanks
Printable View
I must forbid the running of another instance of my app if itsd already running. I tried if (hInstance == hPrevInstance) but that obviously didnt work.
How can this be achieved?
Thanks
One way:
Create a named event using CreateEvent(). When another instance of your app runs, you can detect if the event has been created.
ggCode:#include <iostream>
using namespace std;
#include <windows.h>
int main()
{
HANDLE appRunningEvent = CreateEventA(0, FALSE, FALSE, "MyApp");
if (!appRunningEvent)
{
cerr << "CreateEvent() failed: " << GetLastError() << endl;
return 1;
}//if
if (GetLastError() == ERROR_ALREADY_EXISTS)
{
cout << "An instance of this app is already running." << endl;
return 2;
}//if
cout << "No other instances running." << endl;
Sleep(30 * 1000);
CloseHandle(appRunningEvent);
return 0;
}//main
Ah sounds logical to me! Cool, thanks. Is this thread safe, though?
But what if the application crashes before the CloseHandle is called? No other application will be allowed to run, as the event will still exist?
When your applications exits (or crashes) windows will free up any resources used by your program.
Roger, it works, thanks a lot.
>> Is this thread safe, though?
Only one thread in your application should be doing this anyways. If two of your processes call CreateEvent() at the same time, one of them should always return ERROR_ALREADY_EXISTS.
gg