The following code demonstrates how to detect if there is an instance of your application already running. If detected, it will bring that application to the foreground, and then terminating the current application. This is useful in instances where you want to ensure that only one instance of your application is running.
<code>
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
class AppMain
{
[DllImport("user32.dll")] private static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")] private static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);
[DllImport("user32.dll")] private static extern bool IsIconic(IntPtr hWnd);
private const int SW_HIDE = 0;
private const int SW_SHOWNORMAL = 1;
private const int SW_SHOWMINIMIZED = 2;
private const int SW_SHOWMAXIMIZED = 3;
private const int SW_SHOWNOACTIVATE = 4;
private const int SW_RESTORE = 9;
private const int SW_SHOWDEFAULT = 10;
static void Main()
{
// get the name of our process
string proc=Process.GetCurrentProcess().ProcessName;
// get the list of all processes by that name
Process[] processes=Process.GetProcessesByName(proc);
// if there is more than one process...
if (processes.Length > 1)
{
// get our process
Process p = Process.GetCurrentProcess();
int n=0;
if (processes[0].Id==p.Id) n=1; // Assuming only two instances of this process is presnt right now.
IntPtr hWnd=processes[n].MainWindowHandle;
// if iconic, we need to restore the window
if (IsIconic(hWnd)) {
ShowWindowAsync(hWnd, SW_RESTORE);
}
// bring it to the foreground
SetForegroundWindow(hWnd);
// exit our process
return;
}
// ... continue with your application initialization here.
}
}
</code>
I know what you are thinking .. Can't this be done using Mutex ?! Yup it can surely be done ! In fact it is easier to do it using Mutex class for this kind of a requirement. But then when i was trying some of the classes in System.Diagnostics namespace, i saw a particular snippet which does a similar thing to get the job done. And this is what i ended up with .. kewl !