tags:

views:

305

answers:

2

I have an application, "myprogram.exe", which calls functions and code inside a dll, one of this functions that "myprogram.exe" calls create a new instance of a winform, "MyForm.cs" and then show it using form.show();.

I can have 'n' number of "myprogram.exe" instances running, but I want to have only one instance of "MyForm.cs" for each instance of "myprogram.exe".

The problem that I have is that even thought I'm using mutex inside "MyForm.cs" to create a mutex and them ask if an instance of it is already running, sometimes, it creates another instance, despite the mutex.

Is there another way that I can use to validate if an instance of "myprogram.exe" has already created an instance of "MyForm.cs".

+2  A: 

As per @Joe's comment, the problem is likely to be in the implementation of the Mutux.

This answer to another question demonstrates the right way to do it:

K. Scott Allen has a good write up on using a Mutex for this purpose and issues you'll run into with the GC.

If I want to have only one instance of the application running across all sessions on the machine, I can put the named mutex into the global namespace with the prefix “Global\”.

[STAThread]
static void Main() 
{
   using(Mutex mutex = new Mutex(false, "Global\\" + appGuid))
   {
      if(!mutex.WaitOne(0, false))
      {
         MessageBox.Show("Instance already running");
         return;
      }

Application.Run(new Form1());
   }
}
Colin Pickard
Thanks. I was about to post a similar question and I found this answer extremely helpful!!
bdhar
+1  A: 

I post below link, since I could not find any related article in C++ and MFC. Therefore, For C++, MFC and Win32 you can use http://flounder.com/nomultiples.htm

baris_a