2014
11.18

Recently I was tasked to develop an application to keep track the outgoing items from the warehouse. Since it was style like a POS machine, I need to limit the instance of Windows Form application to only one.

To do this we’re going to need a “locking” mechanism. So before launching the Form, we need to check whether the lock is ON or OFF. We can use Mutex object as the lock.

public Mutex(
	bool initiallyOwned,
	string name
)
initiallyOwned
Type: System.Boolean

true to give the calling thread initial ownership of the named system mutex if the named system mutex is created as a result of this call; otherwise, false.

name
Type: System.String

The name of the Mutex. If the value is null, the Mutex is unnamed.

To ensure the unique-ness of Mutex’s name, I used GUID as name (in Visual Studio, Tools -> Create GUID)

vs-guid

This is the final code:

using System;
using System.Threading;
using System.Windows.Forms;

namespace MyPOS
{
	static class Program
	{
		static Mutex mutex = new Mutex(true, "{37D26ECE-1F4F-42BC-9C23-11A9DAA8DCCA}");

		[STAThread]
		static void Main()
		{
			//Grab the lock
			if (mutex.WaitOne(TimeSpan.Zero, true))			
				Application.EnableVisualStyles();
				Application.SetCompatibleTextRenderingDefault(false);
				Application.Run(new Form1());

				//when the application is finished, release the lock
				mutex.ReleaseMutex();
			}
			else
			{
				//Lock is already used
				MessageBox.Show("Only one instance allowed");
			}
		}
	}
}

I hope it helps, cheers!

GD Star Rating
a WordPress rating system
How To Create Single Instance Windows Form Application, 3.0 out of 5 based on 1 rating

Incoming Search Term

Advertise Here

No Comment

Add Your Comment