Prevent starting multiple instances of a Windows Forms application.

Thursday, October 30, 2008 11:52
Posted in category Windows

There are situations where you do not want a user to start multiple instances of the same Windows Forms application more then once. There are solutions for this out there, that require writing some file and locking it (sort of File Share Witness thingy) and solution that check the running processes on the machine. (What if the user renames the executable?)

I have found a simple solution that works;

In the Main() method of you program, replace this line:

Application.Run(new FormMain());

With this code:

bool isNew;
Mutex mutex = new Mutex(true, Application.ProductName, out isNew);
if (isNew)
{
 Application.Run(new FormMain());
 mutex.ReleaseMutex();
}
else
{
MessageBox.Show("Another instance of " + Application.ProductName + " is already running.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}

You can leave a response, or trackback from your own site.
Tags: , , ,

Leave a Reply

You must be logged in to post a comment.