Home
Manage Your Code
Snippet: Creating a single instance WinForm application per user. (C#)
Title: Creating a single instance WinForm application per user. Language: C#
Description: Here is a (partial) example on how to create a single instance WinForm. The stuff you need to write (very little) is explained in the usage section. Views: 132
Author: digitalWraith .net Date Added: 4/2/2008
Copy Code  
1using System;
2using System.Reflection;
3using System.Threading;
4using System.Windows.Forms;
5
6namespace SingleInstanceWinFormApplication
7{
8	static class Program
9	{
10		/// <summary>
11		/// The main entry point for the application.
12		/// </summary>
13		[STAThread]
14		static void Main()
15		{
16
17			bool firstApplicationInstance;
18
19			string mutexName = Application.UserAppDataPath.Replace("\\", "+") + Assembly.GetEntryAssembly().FullName;
20
21			Application.EnableVisualStyles();
22			Application.SetCompatibleTextRenderingDefault(false);
23
24			using (Mutex mutex = new Mutex(false, mutexName, out firstApplicationInstance))
25			{
26
27				if (!firstApplicationInstance)
28				{
29					Application.Run(new frmAlreadyRunning());
30				}
31				else
32				{
33					Application.Run(new frmMain());
34				}
35		
36			}
37
38		}
39
40	}
41
42}
43
Usage
Create your project.  I always rename Form1.cs to frmMain.cs.  Create a second form to 
display when a second instance has been created (frmAlreadyRunning.cs).  frmAlreadyRunning
should be very simple.  Just enough to show what happened and provide a graceful exit.      
Notes
Application.UserAppDataPath.Replace("\\", "+") is required if you want the user to be limited by not ALL/ANY users on a system.