Preventing Multiple instances of the same application
June 12th, 2007 by Chris
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.
C#:
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.
Technorati Tags: C#, Windows.Forms, .NET
Posted in Windows Forms |
March 5th, 2008 at 10:12 am
Is System.Diagnostics.Process scoped globally across the local machine or is it specific to the current user session?
I’m asking because developers working on terminal services friendly applications may not be able to use this method if it applies globally to the entire computer.
Andre Ranieri