Home
Manage Your Code
Snippet: Creating a single instance application per machine. (C#)
Title: Creating a single instance application per machine. Language: C#
Description: Here is code for creating an application that is restricted to a single instance on a machine. Views: 103
Author: digitalWraith .net Date Added: 4/2/2008
Copy Code  
1using System;
2using System.Reflection;
3using System.Threading;
4
5namespace SingleInstanceApplication
6{
7	class Program
8	{
9		static void Main(string[] args)
10		{
11			bool firstApplicationInstance;
12
13			string mutexName = Assembly.GetEntryAssembly().FullName;
14
15			using (Mutex mutex = new Mutex(false, mutexName, out firstApplicationInstance))
16			{
17
18				if (!firstApplicationInstance)
19				{
20					Console.WriteLine("This application is already running.");
21					Console.WriteLine("[ENTER]");
22					Console.ReadLine();
23				}
24				else
25				{
26					Console.WriteLine("Do something interesting.");
27					Console.WriteLine("[ENTER]");
28					Console.ReadLine();
29				}
30			}
31		}
32	}
33}
34
Usage
bool firstApplicationInstance;
string mutexName = Assembly.GetEntryAssembly().FullName;

using (Mutex mutex = new Mutex(false, mutexName, out firstApplicationInstance))
{
  if (!firstApplicationInstance)
    // alreday running
  else
    // do your thing...
}
Notes
From: Essential C# 2.0 by Mark Michaelis. It is a very useful book. I have changed it a bit to suit the problem I am working on but it works.