Tag Archives: Mutex
How to allow only one application instance
The following code will ensure that your application can only have one instance active. If the user tries to open the application again while the application is already running then the application will simply quit (in this case after showing a message).
For this to work we will need to modify the Program.cs to check with the use of Mutex if the application is already running or not before we open the main form. Our check will take place in the Main method.
Your code in Program.cs should look like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | using System; using System.Reflection; using System.Runtime.InteropServices; using System.Threading; using System.Windows.Forms; namespace WindowsFormsApplication1 { static class Program { [STAThread] static void Main() { /* Retrieve the application Guid attribute. Alternative you can simply use the application name to initialize the Mutex * but it might be risky as other programs might have similar name and make use of the Mutex class as well. */ GuidAttribute appGuid = (GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), true)[0]; // The boolean that will store the value if Mutex was successfully created which will mean that our application is not already running. bool createdNew = true; // Initialize the Mutex object. using (Mutex mutex = new Mutex(true, appGuid.Value, out createdNew)) { /* If Mutex was created successfully which means our application is not running run the application as usual * or else display a message and close the application.*/ if (createdNew) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } else { MessageBox.Show("Application is already running"); } } } } } |
Feel free to modify the example to suit your needs.