Wednesday, January 03, 2007

As always, you want only a single instance running of your program.  To do this you have to make use of the Mutex object.  By using reflection we get the executing name of our application.  We will use it for checking if there’s already an instance.

The Mutex object can be used for interprocess synchronization.  With this we could check if our application is already running.  With the waitone method we can request the  ownership of our mutext object.  If it return false, then there’s already a process running using this mutex object.

Example code :

using System.Reflection;
using System.Threading;

…..

private static Mutex s_Mutex;

/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
s_Mutex = new Mutex(true, Assembly.GetExecutingAssembly().GetName().Name);

if (s_Mutex.WaitOne(0, false))
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
else
MessageBox.Show("Already an instance running", "your application", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}

1/3/2007 9:41:28 AM (Romance Standard Time, UTC+01:00)  #     |