Friday, May 09, 2014

Launching a Single Instance of an Application

It is easy to launch a new process in C#. The following code sample launches the built-in Windows Calculator application:

{
    Process.Start("calc.exe");
}

However, the problem with this code is if it is called multiple times in an application (like on a button click), multiple copies of the Windows Calculator will be started. In some situations that may be desired, but often only one instance of the application is desired.

The following code demonstrates how to launch a new process in C# if it is not already running or set focus to the application if it is already running:

[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool ShowWindow(IntPtr hWnd, uint nCmdShow);
 
private const uint SW_SHOWNORMAL = 1;
 
[DllImport("user32.dll", SetLastError = true)]
private static extern bool BringWindowToTop(IntPtr hWnd);
 
private void cmdLaunchOnce_Click(object sender, EventArgs e)
{
    try
    {
        Process calculator = Process.GetProcessesByName("calc").FirstOrDefault();
        if (calculator == null)
        {
            Process.Start("calc.exe");
        }
        else
        {
            ShowWindow(calculator.MainWindowHandle, SW_SHOWNORMAL);
            BringWindowToTop(calculator.MainWindowHandle);
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, "Launch Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

Things to note:

  • When searching for the process, you do not include the “.exe” part of the executable name.
  • The call to ShowWindow will restore the Calculator window if it has been minimized.
  • The call to BringWindowToTop causes the Calculator window to become the top-most window.

No comments: