Click to See Complete Forum and Search --> : allowing only 1 instance of app
softwareguy74
Jan 4th, 2001, 01:13 PM
Hi,
I want to prevent the user from starting more than 1 instance of my app.
I would assume that I would put some code in the WinMain function to detect if a instance allready exists and then exit but not sure how I would implement it.
I'm using VC++ W/OUT MFC.
Any help would be appreciated..
Dan
parksie
Jan 4th, 2001, 01:38 PM
Try this:
#include <windows.h>
int __stdcall WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
HANDLE hMutex = CreateMutex(NULL, TRUE, "Test Windows Program - only 1 instance");
if(GetLastError() == ERROR_ALREADY_EXISTS) {
MessageBox(NULL, "Already an instance", "Error", MB_OK);
return -1;
}
MessageBox(NULL, "This is first instance", "Okay", MB_OK);
ReleaseMutex(hMutex);
CloseHandle(hMutex);
return 0;
}
parksie
Jan 6th, 2001, 07:48 AM
It creates a mutually exclusive handle. IE: only one can exist at the same time. So, what it does is it tries to create one. If one exists with that name then the handle to the existing one is returned, and GetLastError() returns ERROR_ALREADY_EXISTS.
When the app has finished, it closes its handle onto the mutex. If all the mutex's threads have ended, the mutex is released from the system.
vbforums.com
Copyright Internet.com Inc., All Rights Reserved.