MFC Application: How can I limit my application to one instance?
Q: How can I limit my application to one instance?
A: You need to create a named mutex semaphore when you start your application. When the second one starts it tries to get access to the mutex but will fail...
Code:
// app.h
class CYourApp : public CWinApp
{
...
private:
HANDLE hMutex;
};
// app.cpp
BOOL CYourApp::InitInstance()
{
// Create mutex
hMutex = ::CreateMutex(NULL, TRUE, "GlobalMutex");
switch(::GetLastError())
{
case ERROR_SUCCESS:
// Mutex created successfully. There is no instance running
break;
case ERROR_ALREADY_EXISTS:
// Mutex already exists so there is a running instance of our app.
return FALSE;
default:
// Failed to create mutex by unknown reason
return FALSE;
}
}
Last edited by Andreas Masur; July 24th, 2005 at 04:46 PM.
Re: MFC Application: How can I limit my application to one instance?
First of all, thank you for this post. I want to update it with additional specification. In my case I needed to limit the app to single instance across all terminal server sessions (i.e., multiple users logged on at the same time in Windows XP).
* The Best Reasons to Target Windows 8
Learn some of the best reasons why you should seriously consider bringing your Android mobile development expertise to bear on the Windows 8 platform.