Tag Archives: Mutex
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:
static class Program
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);
// 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.*/
MessageBox.Show("Application is already running");
Feel free to modify the example to suit your needs.