tags:

views:

909

answers:

4

In a C# Windows Forms application I want to detect if another instance of the application is already running. If so, activate the main form of the running instance and exit this instance.

What is the best way to achieve this?

A: 

Here is what I'm currently doing in the application's Program.cs file.

// Sets the window to be foreground
[DllImport("User32")]
private static extern int SetForegroundWindow(IntPtr hwnd);

// Activate or minimize a window
[DllImportAttribute("User32.DLL")]
private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
private const int SW_RESTORE = 9;

static void Main()
{
    try
    {
     // If another instance is already running, activate it and exit
     Process currentProc = Process.GetCurrentProcess();
     foreach (Process proc in Process.GetProcessesByName(currentProc.ProcessName))
     {
      if (proc.Id != currentProc.Id)
      {
       ShowWindow(proc.MainWindowHandle, SW_RESTORE);
       SetForegroundWindow(proc.MainWindowHandle);
       return;   // Exit application
      }
     }


     Application.EnableVisualStyles();
     Application.SetCompatibleTextRenderingDefault(false);
     Application.Run(new MainForm());
    }
    catch (Exception ex)
    {
    }
}
Dean Hill
+5  A: 

Scott Hanselman answers on you question in details.

aku
A: 

Aku, that is a good resource. I answered a question similar to this one a while back. You can check my answer here. Even though this was for WPF, you can use the same logic in WinForms.

Dale Ragan
Actually I learned this trick from Sells book too. But Scott's article just seats among my bookmarks :)
aku
+2  A: 

You can use such detection and activate your instance after it:

        // Detect existing instances
        string processName = Process.GetCurrentProcess().ProcessName;
        Process[] instances = Process.GetProcessesByName(processName);
        if (instances.Length > 1)
        {
            MessageBox.Show("Only one running instance of application is allowed");
            Process.GetCurrentProcess().Kill();
            return;
        }
        // End of detection
nihi_l_ist
Thanks, I really like your solution.
Sharique