codebrothers.net :: Home  >  Matthias Denkmaier
User: Guest  Login
Matthias Denkmaier
C# - what else?
Blog search:  
How to ensure that only a single program instance is running

Often you want to ensure that only a single instance of your application is running on a maschine.

Therefore you need a mechanism to determine if an instance is alread<y running to avoid starting another instance.

The following code does exactly that by using a so called Mutex a special object also used for interproces snyc.

bool isSingleInstance = false;
string appIdentifier = "Global\\YourApplicationIdientifierString";
using(System.Threading.Mutex m = new System.Threading.Mutex(true, appIdentifier, out isSingleInstance ))
{
   if (isSingleInstance)
   {
      Application.Run (new MainForm());
   }
   else
   {
      MessageBox.Show("There is alraeady an instance running!");
   }
}

Note: By using the ’Global’ prefix for your application identifier you can ensure a single instance for the whole maschine and not only for the current user session/desktop.

Share this post: Email it!
Posted:  2/9/2007 8:38:38 AM  by  mdenkmaier
Tags:  How toC#Development
No comments, yet!
Leave a Comment

Name required

Your URL

Comments (required)