There is a number of methods.
First method is the simplest works if you don't care about the same program located somewhere else on your disk(s), because — how would you know this is exactly the same? If you entry assembly is not strong named, all other assembly attributes does not provide reliable identification to tell is the assembly in different directory is the "same application" as the one you're running. So, let's assume you want to detect a second instance of the same application which has the same main module of its entry assembly with the same full file name. Also, a match in the properties of the process can be used (see below). To find this module file and process instance for currently running application, do the following:
string mainModuleFile = System.Reflection.Assembly.GetEntryAssembly().Location;
System.Diagnostics.Process currentProcess = System.Diagnostics.Process.GetCurrentProcess();
Now, let's take care about first instance if it is already running. First, iterate all processes in the system using
System.Diagnostics.Process.GetProcesses
. For each process in the iteration loop, find its main module using
Process.MainModule
instance property. This property returns the instance of the class
System.Diagnostics.ProcessModule
, and
System.Diagnostics.ProcessModule.FileName
give you the full-path file name to compare with the one of your process you're currently running. If you have a match, the instance running this code is not the first. You can take required actions and exit the application.
In principle, this method can be modified to use a little bit different criterion for the match, using additional Process properties but not requiring exact match of the full path name; the properties like
ProcessName
,
Modules
,
MainWindowTitle
(if applicable),
MainModule.ProcessName
, etc.; in this way, a previous instance of the "same" application can be detected even if its executable file(s) is different. Again, no combination of the process properties can guarantee this is the "same" application.
This is not all…
To be continued…
—SA