tags:

views:

430

answers:

3

I have created one MFC Dialog Based application.now if i am running the application its working fine,instead of closing the application i minimized the application,if i run the application again,i am getting the Dialog.

I want to prevent the calling of application multiple times. please give me the code

A: 

The easiest way is to check in your Main() if a process of the same name as your program is already running, and quit if it is.

A google search will quickly find the relevant code, e.g. This forum post should be suitable

Jason Williams
+5  A: 

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

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;
}

Ensure that the mutexname is unique, use VS to generate a GUID and use that in string form as the mutex name.

ChrisBD
what is mutexname, i am not getting plz will you give the example
i am using vc++ 6.0
"mutexname" is a string value that you supply. You'll need to replace that in your actual code. The string needs to be as unique as possible. The easiest way is to use the GUID generator in Visual Studio to give you a GUID string e.g."{D07E6400-40D6-493a-8470-542A14102CB6}". Replace mutexname with that.
ChrisBD
Ah I see that you're using VS 6 - I can't remember if that has a GUID generator, in which case use the one that I've supplied above.
ChrisBD
humm it is difficult,bcz still i dont know in vc++ 6.0 how to use the GUID generator in VS to get the GUID string,
Unfortunately I'm using VS2008 and I can't remember whether VS6 has a tool for creating GUIDs. For me I have the option under the Tools menu to "Create GUID" I then selected the registry version and copied that to give me the string that I placed above.You don't have to use a GUID for your mutexname, but its a surefire way of ensuring that your string is unique. If you wanted you could use any string e.g. "I love sausages with mashed potato and gravy" and it would still work until you came across someone else who liked sausages, mash and gravy. :)
ChrisBD
I've edited my answer to show what to do with the return value of the function.
ChrisBD
@smith, it doesn't need to be a GUID, you could just as easily use "plzsendmetehcodezkthxbye" :)It just needs to be a string unlikely to be used by another application's mutex.
Paul Dixon