BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Windows Programming
.NET 1.1+

Allowing Only One Instance of an Application

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 named Process. 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, two static 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.");
        return;
    }
    // End of detection

    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    Application.Run(new Form1());
}

NB: The standard Main method varies slightly according to the version of the .NET framework being used. Always ensure that the detection code is placed immediately following the method declaration.

19 November 2007