Saturday, December 8, 2012

Allowing Only One Instance of an Application in Windows Forms C#

Standard Windows Forms applications can be launched multiple times and each instance used completely independently of the others. However, sometimes it is important to restrict the user in launching a single instance of a program.

The Process Class
The System.Diagnostics namespace contains a class namedProcess. This class contains functionality that allows interrogation of the processes that are currently executing in Microsoft Windows. The class can be used to determine if any other instances of an application are running and, if one is, a decision can be made to stop the current program.

Detecting Other Instances
To determine if another instance of a program is executing, twostatic methods of the Process class are used. Firstly, a call to the GetCurrentProcess method is made. This returns the current program's process details including its name within the returned object's ProcessName property.
Once the process name is known, the GetProcessesByName method can be used to return an array of Process objects with one representing each instance of the named software. This list includes the current program so if there is more than one element in the array there must be other running instances of the software.

Adding Detection to an Application
Using the two methods described, a simple test can be made within the Main method of an application. The following C# code demonstrates this by checking the number of matching processes and showing an error message if another instance is active. The method is then simply returned from to close the application. This is done before the main form of the application is loaded.

static void Main()
     // Detect existing instances
     string processName = Process.GetCurrentProcess().ProcessName;      
     Process[] instances = Process.GetProcessesByName(processName);
    if (instances.Length > 1)
             MessageBox.Show("This application is already running.");
    // End of detection Application.EnableVisualStyles();                
    Application.Run(new Form1());

No comments:

Post a Comment