This is in C# with .NET 2.0.
In the .NET framework 2.0 we use the System.Diagnostics.Process class.
To get the current process:
Process currentProcess = Process.GetCurrentProcess();
To get a list of processes by name:
Process[] processesWithSameName = Process.GetProcessesByName("MyProcessName");
Each running process has its own unique ID.
Process[] processesWithSameName = Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName); foreach (Process process in processesWithSameName) { if (process.Id != currentProcess.Id) { MessageBox.Show("Another process with the same name was detected."); } }
See this thread on Channel 9.
[STAThread] static void Main() { bool grantedOwnership; using (System.Threading.Mutex mtxSingleInstance = new System.Threading.Mutex(true, "A2907A9C-63D7-474e-ADA6-EA910EF1493D", out grantedOwnership)) { if (grantedOwnership) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } else { ShowWindow(FindWindow(null, "Form1"), SW_RESTORE); } } } private const int SW_RESTORE = 9; [DllImport("user32.dll")] private static extern IntPtr FindWindow(string lpClassName, string lpWindowName); [DllImport("user32.dll")] private static extern int ShowWindow(IntPtr hwnd, int cmndShow);
This code uses a mutex. The first instance of the application will acquire a lock on the mutex. Then when the application is started subsequently it will not be able to acquire the mutex. The mutex will be released when the first application exits.
The code also uses interop to access the Win32 functions FindWindow() and ShowWindow().