Knowledge.ToString()

How to run a single instance of WinForm application?

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>
	/// The main entry point for the application.
	/// </summary>
	[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();
	}
}

Share

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *