Thursday, 9 October 2008

Stop multiple instances of your windows app running

I needed to stop users from starting up more than one copy of the MyTime app running and I found this link to help.

I changed where the code actually runs, I think its a bit better this way.

1. Open up the Program.cs file.

2. Add System.Threading into the using list.

3. Paste this in the class declaration
private static Mutex mutex;
private static string mutexName = "MyTime.Mutex";

4. Paste this in the main() method before any other code runs.
try
{
mutex = Mutex.OpenExisting(mutexName);

//since it hasn’t thrown an exception, then we already have one copy of the app open.
MessageBox.Show("A copy of MyTime is already open.",
"MyTime", MessageBoxButtons.OK, MessageBoxIcon.Information);

//use this command as we haven't called the run method of the application
Environment.Exit(0);
}
catch
{
//since we didn’t find a mutex with that name, create one
mutex = new Mutex(true, mutexName);
}

//Hook up the Application Exit event to release the mutex so that the app can re-open correctly.
Application.ApplicationExit += new EventHandler(delegate { mutex.ReleaseMutex(); });


5. Thats it. Test it!


Don't think there is much else to this. Any questions let me know.

No comments:

Free Hit Counter