Start only one instance of MFC Dialog Based Application

I created an MFC Dialog Based application.

I started the application and it worked fine. Now that it is running, I start the application again and it launches another instance.

But I don't want his behavior; If the application is already running, I want to prevent new instances from being created.

Please give me the code.

0


a source to share


3 answers


Try to call the following function in your main before you call your application dialog class. If it returns False then don't create the dialog and exit instead.

BOOL init()
{
   HANDLE mutex = CreateMutex(NULL, FALSE, "mutexname");
   if(mutex == NULL)
   {
      return FALSE;
   }

   if (GetLastError() == ERROR_ALREADY_EXISTS)
   { 
       /* You only need the message box if you wish to notify the user 
          that the process is running*/
       MessageBox("Another instance is already running.");
       return FALSE;
   }

   return TRUE;
} 

      



Make sure the mutex name is unique, use VS to generate the GUID and use that in string form as the mutex name.

+8


a source


+1


a source


The easiest way is to check your Main () if a process with the same name as your program is already running, and exit if there is one.

A google search will quickly find the matching code, eg. This forum should be suitable

0


a source







All Articles