Thursday 28 February 2008

Preventing Multiple instances of the same application

As many programmers have come across, sometimes you want to prevent your app being launched more than once. This is a desirable function for many reasons. This can be used when you're app relies on writing or reading from files, and to prevent locking of files and possible corruption, you only want your app to run once. If you're writing something that is going to be only useful in a single instance, you can check and prevent multiple instances being run. The code snippet below details how to perform this check at the launch of your app.

using System;

using System.Windows.Forms;

public partial class MainDesktop : System.Windows.Window

{

public MainDesktop()

{

if (System.Diagnostics.Process.GetProcessesByName(System.Diagnostics.Process.GetCurrentProcess().ProcessName).Length == 1)

{

/// App initilization code here

}

else

{

this.Close();

}

}

}

Put this code in the main method of your app. This way when it runs, it checks and if finds another process with the same name, causes the new app to close instantly.

Share:

0 comments:

Post a Comment