How to prevent program from running twice??

How to prevent program from running twice??

Post by Caesar Wan » Fri, 02 Apr 2004 18:57:59


Hello:

I've developed one MFC program.
But the OS reboot each time i open the program twice and then close
them.
The program runs normally when only one program being opened each
time.

How can i stop opening the program when the program is opened?
(How to detect program running in MFC? )


thanks for your help ^^
 
 
 

How to prevent program from running twice??

Post by Scott McPh » Fri, 02 Apr 2004 22:01:30


Make a nice long unique name, that only your program knows, and attempt
to create a mutex using that name. The result tells you whether such a
mutex already exists.

BOOL CSomeApp::InitInstance()
{
// Exit if another instance of this program is running.
m_hMutex = CreateMutex(NULL, TRUE, "unique string");
if (!m_hMutex || GetLastError() == ERROR_ALREADY_EXISTS)
{ if (m_hMutex)
{ ReleaseMutex(m_hMutex);
CloseHandle(m_hMutex);
}
return FALSE; // this instance exits
}

...also remember to do the CloseHandle stuff in ExitInstance.


--
Scott McPhillips [VC++ MVP]

 
 
 

How to prevent program from running twice??

Post by uwe.kotycz » Sat, 03 Apr 2004 21:20:59

> Make a nice long unique name, that only your program knows, and attempt

Just a question about a minor point: Why do you call ReleaseMutex
only if GetLastError() == ERROR_ALREADY_EXISTS?
IMO then you should get another error: ERROR_NOT_OWNER
Shouldn't ReleaseMutex been called when the first instance starts?
Something like

BOOL CSomeApp::InitInstance()
{
// Exit if another instance of this program is running.
m_hMutex = CreateMutex(NULL, TRUE, "unique string");
DWORD dwError = GetLastError();

if (m_hMutex != NULL && dwError != ERROR_ALREADY_EXISTS)
ReleaseMutex(m_hMutex);

if (m_hMutex == NULL || dwError == ERROR_ALREADY_EXISTS)
return FALSE;

...

return TRUE;
}

BOOL CSomeApp::ExitInstance()
{
if (m_hMutex != NULL)
CloseHandle(m_hMutex);

return CWinApp::ExitInstance();
}
 
 
 

How to prevent program from running twice??

Post by Scott McPh » Sun, 04 Apr 2004 08:51:32


I don't remember why I acquire the mutex ownership. Something that
might have helped in a situation long ago, when a service and security
were involved (I think). It is probably overkill and your observation
seems correct.

--
Scott McPhillips [VC++ MVP]
 
 
 

How to prevent program from running twice??

Post by urbis7 » Sat, 17 Apr 2004 19:17:24


Hi, just look for the class "CWinAppEx" in www.codeproject.com"