Click here to Skip to main content
15,885,985 members
Articles / Programming Languages / C#
Article

Detect if another process is running and bring it to the foreground

Rate me:
Please Sign up or sign in to vote.
4.54/5 (34 votes)
30 Sep 2002 306.4K   113   39
Sometimes, you only want one instance of your application running. This is a C# implementation that tests to see if an instance of your application is already running, and brings it to the foreground if it is.

Introduction

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 (restoring its window state if iconic), 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.

This code was put together using the prior work of Taylor Wood ("Window Hiding in C#") and a message in the C# forum posted by David Wengier illustrating the use of the Process class. Without their help, this would have taken me several hours to put together, instead of a few minutes!

The Code

C#
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)
        {
            // Assume there is our process, which we will terminate, 
            // and the other process, which we want to bring to the 
            // foreground. This assumes there are only two processes 
            // in the processes array, and we need to find out which 
            // one is NOT us.

            // get our process
            Process p=Process.GetCurrentProcess();
            int n=0;        // assume the other process is at index 0
            // if this process id is OUR process ID...
            if (processes[0].Id==p.Id)
            {
                // then the other process is at index 1
                n=1;
            }
            // get the window handle
            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.
    }
}

Conclusion

This code is a great example of interfacing with Win32 libraries and using some esoteric functions in .NET.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Architect Interacx
United States United States
Blog: https://marcclifton.wordpress.com/
Home Page: http://www.marcclifton.com
Research: http://www.higherorderprogramming.com/
GitHub: https://github.com/cliftonm

All my life I have been passionate about architecture / software design, as this is the cornerstone to a maintainable and extensible application. As such, I have enjoyed exploring some crazy ideas and discovering that they are not so crazy after all. I also love writing about my ideas and seeing the community response. As a consultant, I've enjoyed working in a wide range of industries such as aerospace, boatyard management, remote sensing, emergency services / data management, and casino operations. I've done a variety of pro-bono work non-profit organizations related to nature conservancy, drug recovery and women's health.

Comments and Discussions

 
GeneralRe: Restore the application from notify icon (system tray) Pin
panda122345623-Mar-05 11:48
panda122345623-Mar-05 11:48 
GeneralRe: Restore the application from notify icon (system tray) Pin
kubben13-Dec-05 3:08
kubben13-Dec-05 3:08 
GeneralA little tweak.. if I may... Pin
Anonymous9-Oct-02 11:30
Anonymous9-Oct-02 11:30 
GeneralRe: A little tweak.. if I may... Pin
Marc Clifton9-Oct-02 15:41
mvaMarc Clifton9-Oct-02 15:41 
GeneralRe: A little tweak.. if I may... Pin
pburns29-Apr-03 7:45
pburns29-Apr-03 7:45 
GeneralDerivable app class Pin
mav428-Oct-02 6:16
sussmav428-Oct-02 6:16 
GeneralRe: Derivable app class Pin
Marc Clifton8-Oct-02 6:56
mvaMarc Clifton8-Oct-02 6:56 
GeneralAgree with David Stone Pin
Nish Nishant4-Oct-02 22:48
sitebuilderNish Nishant4-Oct-02 22:48 
GeneralRe: Agree with David Stone Pin
Marc Clifton5-Oct-02 9:12
mvaMarc Clifton5-Oct-02 9:12 
GeneralNever mind Pin
Marc Clifton5-Oct-02 9:23
mvaMarc Clifton5-Oct-02 9:23 
GeneralRe: Agree with David Stone Pin
David Stone8-Oct-02 8:50
sitebuilderDavid Stone8-Oct-02 8:50 
GeneralGreat article... Pin
David Stone2-Oct-02 15:02
sitebuilderDavid Stone2-Oct-02 15:02 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.