5,286,006 members and growing! (20,694 online)
Email Password   helpLost your password?
Languages » C# » How To     Intermediate

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

By Marc Clifton

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.
C#, .NET, Win2K, WinXP, Windows, Visual Studio, Dev

Posted: 30 Sep 2002
Updated: 30 Sep 2002
Views: 110,889
Announcements
Want a new Job?



Search    
Advanced Search
Sitemap
27 votes for this Article.
Popularity: 6.10 Rating: 4.26 out of 5
3 votes, 12.0%
1
0 votes, 0.0%
2
2 votes, 8.0%
3
5 votes, 20.0%
4
15 votes, 60.0%
5

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

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

About the Author

Marc Clifton


Mvp, Protector, Supporter
Marc is the creator of two open source projets, MyXaml, a declarative (XML) instantiation engine and the Advanced Unit Testing framework, and Interacx, a commercial n-tier RAD application suite.  Visit his website, www.marcclifton.com, where you will find many of his articles.

Marc lives in Hudson, NY with his son Ian, who attends the Hawthorne Valley School. To contact Marc, email him at marc.clifton@gmail.com.
Occupation: Architect
Company: Interacx
Location: United States United States

Other popular C# articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 25 of 32 (Total in Forum: 32) (Refresh)FirstPrevNext
Subject  Author Date 
QuestionUse this article In Windows CE 5.0memberTyler459:47 10 Jan '07  
GeneralHow to get it work with Compact Framework ?memberMikael Braad Nielsen2:28 26 Jan '06  
GeneralRe: How to get it work with Compact Framework ?memberGizz0:59 15 Nov '06  
AnswerRe: How to get it work with Compact Framework ?membersiSidon6:10 23 Apr '07  
GeneralWhat about notification area??memberRaananan9:24 28 Nov '05  
GeneralRe: What about notification area??memberkubben4:05 13 Dec '05  
QuestionNice, butmemberChazsoft4:18 7 Oct '05  
GeneralWhat if?memberSuper Lloyd2:19 27 Jun '05  
GeneralApp name changed?memberTNTVN20:18 6 Dec '04  
GeneralGreat article, almost everything I needmembersnappa12:58 1 Mar '04  
GeneralIs there a 100% NET way to do this?memberm.chung4:01 14 Feb '04  
GeneralRe: Is there a 100% NET way to do this?editorMarc Clifton5:39 15 Feb '04  
GeneralAnother approach: using mutexesmemberGuido_d3:58 20 Jan '04  
GeneralRe: Another approach: using mutexeseditorMarc Clifton4:07 20 Jan '04  
GeneralHiding problemmemberNeoshid1:02 21 Oct '03  
GeneralRe: Hiding problemsussC# newuser13:59 23 Apr '05  
GeneralMore than 15 characters ProcessNamememberZ42Cool0:19 17 Jul '03  
GeneralRe: More than 15 characters ProcessNamesussAnonymous10:12 20 Aug '03  
GeneralCoolmemberKant17:17 6 Apr '03  
GeneralRestore the application from notify icon (system tray)sussQui3:19 17 Oct '02  
GeneralRe: Restore the application from notify icon (system tray)memberpanda122345612:48 23 Mar '05  
GeneralRe: Restore the application from notify icon (system tray)memberkubben4:08 13 Dec '05  
GeneralA little tweak.. if I may...sussAnonymous12:30 9 Oct '02  
GeneralRe: A little tweak.. if I may...memberMarc Clifton16:41 9 Oct '02  
GeneralRe: A little tweak.. if I may...memberpburns8:45 29 Apr '03  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 30 Sep 2002
Editor: Nishant Sivakumar
Copyright 2002 by Marc Clifton
Everything else Copyright © CodeProject, 1999-2008
Web11 | Advertise on the Code Project