Powered by |
How to ensure a single instance of the application at a time?As the experience shows there is one proven method to do this: the creation of known kernel object. As a matter of fact when you use so called named kernel objects (like event, mutex, semaphore etc.) they are global over the system. You can easily check if there is another object with the same name. Of couse you'd better to invent unique name for this. Remember that all kernel objects share the same name space. See the classic sample for Win32 application:
int WINAPI WinMain(...) or MyApp()::InitInstance()
{
HANDLE hAnyKernelObject = CreateMutex(NULL, FALSE,
"{E27D1C1E-B4D8-4439-83B4-0173E03C5D11}");
// Use guidgen.exe to get your guid for this or just invent long specific name.
if (GetLastError() == ERROR_ALREADY_EXISTS)
return FALSE;
}
// Code for execution if no instance found.
MyApp()::ExitInstance()
{
// ...
CloseHandle(hAnyKernelObject);
return 0;
}
Sample project is available. The following link describes another aspects of the problem: Avoiding Multiple Instances of an Application by Joseph M. Newcomer.
|