Creating a Single Instance Application in .NET

Provided by Molly Pell, Senior Systems Analyst

When working with Windows Forms applications, you may want to ensure that only one copy of your .exe runs at a time. In Visual Basic 6, you could use the Forms property to get a list of all open forms, or use App.PrevInstance to see if your application was already running. In .NET, however, similar functionality is not available.

Instead, use the System.Threading.Mutex class. To use this technique, generate a named Mutex at the application’s entry point, and lock it. When a second instance is started, it will fail since it can’t be locked.

Example

To use this code, put it in your project’s entry point:

   ' VB
   Dim mut As System.Threading.Mutex = _
   New System.Threading.Mutex(False, Application.ProductName)
   Dim running As Boolean = Not mut.WaitOne(0, False)
   If running Then
       Application.ExitThread()
       Return
   End
If

   // C#
   System.Threading.Mutex mut =
       new System.Threading.Mutex(false, Application.ProductName);
   bool running = !mut.WaitOne(0, false);
   if (running)
   {
       Application.ExitThread();
       return;
   }


Additional Resources

 

 

Thank you! Thank you! I just finished reading this document, which was part of a link in the recent Buzz newsletter. I have printed it for others to read, especially those skeptical on the powers of Access and its capabilities.

Darren D.


View all FMS products for Microsoft Access All Our Microsoft Access Products

 

 

Free Product Catalog from FMS