Free Resources from FMS

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.

 

Free Catalog

 

Creating a Single Instance Application in .NET

Provided by: Molly Pell, Technical Project Manager

Overview

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 (see Mutex Class for details). 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;
   }

More Information

See Microsoft MSDNís Real World Applications Sample for more information about this technique.
 

Return to the tips page