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 theGetCurrentProcess 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.
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.
No comments:
Post a Comment