Running a process only once
We all know that usually the starting point for every WinForms application is the Main() method. Here’s a little trick to ensure that an application of ours runs only once, making an active effort to stop any other instance that could be called if there’s another one already running. Here’s how:
///Application’s entry point
/// </summary>
[STAThread]
static void Main()
{
if(Process.GetProcessesByName(
Process.GetCurrentProcess().ProcessName).GetUpperBound(0)==0)
{
Application.Run(new frmMain());
}
}
Colorized by: CarlosAg.CodeColorizer
The key of all this is the Process class. It belongs to the Systems.Diagnostics namespace, and one of its capabilities is obtaining the name of the current process (via Process.GetCurrentProcess().ProcessName, which returns an string), and another one is obtaining all running process with a given name (Process.GetProcessesByName, which returns an array of Process objects). The if() in that line searches for an already running process with the same name as the one we’re trying to start in the list of all currently running processes and if it’s not found, which is determined by comparing the length of the array containing the found processes with 0, the application starts.




