How to run a single instance of WinForm application?

By | February 5, 2020 | 0 Comment
Category: .Net Tags: ,

Following tutorial provides an example to run a single instance of WinForms application using Mutex. There are multiple ways to achieve the same result but this is kind of neat solution in my opinion.

Add following SingleInstance class in your project.

public static class SingleInstance
{
	static Mutex mutex;
	public static bool Start(string applicationIdentifier)
	{
		bool isSingleInstance = false;
		mutex = new Mutex(true, applicationIdentifier, out isSingleInstance);
		return isSingleInstance;
	}
	public static void Stop()
	{
		mutex.ReleaseMutex();
	}
}

Here is how to use it in Program.cs > Main function

static class Program
{
	/// <summary&gt;
	/// The main entry point for the application.
	/// </summary&gt;
	[STAThread]
	static void Main()
	{
		// Here, you need to pass a guid or any other unique string.
		if (!SingleInstance.Start("0f03c714-b597-4c17-a351-62f35535599a"))
		{
			MessageBox.Show("Application is already running.");
			return;
		}

		Application.EnableVisualStyles();
		Application.SetCompatibleTextRenderingDefault(false);
		Application.Run(new frmMain());

		// mark single instance as closed
		SingleInstance.Stop();
	}
}

About Vishal Monpara

Vishal Monpara is a full stack Solution Developer/Architect with 13 years of experience primarily using Microsoft stack. He is currently working in Retail industry and moving 1's and 0's from geographically dispersed hard disks to geographically dispersed user leveraging geographically dispersed team members.