Click here to Skip to main content
Click here to Skip to main content

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

By , 30 Sep 2002
 

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
United States United States
Member
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 and his blog.
 
Marc lives in Philmont, NY.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
Suggestionworkaround for when process cannot bring other window to foregroundmembertheory200619 Jul '12 - 0:16 
hi Marc
 
nice article - really useful.
 
suggestion - in Windows, sometimes a process is not allowed to bring another window to the foreground.
 
There is a list of conditions here from Microsoft:
 
http://msdn.microsoft.com/en-us/library/windows/desktop/ms633539(v=vs.85).aspx
 
workaround: (VB.NET)
minimise the other window, then show it again:
 
' bring it to the foreground
If Not SetForegroundWindow(hWnd) Then
    'this process could not set the window as foreground.
    '
    'workaround:  minimise the window, then show it::
    ShowWindowAsync(hWnd, SW_SHOWMINIMIZED)
    ShowWindowAsync(hWnd, SW_RESTORE)
End If
 
This works OK on Windows XP Pro.
______
theory2006

GeneralMy vote of 4membertheory200619 Jul '12 - 0:13 
useful article
QuestionUse this article In Windows CE 5.0memberTyler4510 Jan '07 - 8:47 
How can i use it with windows CE 5.0 Device
QuestionHow to get it work with Compact Framework ?memberMikael Braad Nielsen26 Jan '06 - 1:28 
I am a newbi to this stuff, but is there any easy way to get this working on Compact Framework
 
Best Regards
Mikael
AnswerRe: How to get it work with Compact Framework ?memberGizz14 Nov '06 - 23:59 
Apparently not.
AnswerRe: How to get it work with Compact Framework ?membersiSidon23 Apr '07 - 5:10 
This solution works for me
 
public class ThisApp : Form
{
private const int WM_ACTIVATE = 0x0006;
private const int WA_ACTIVE = 1;
 
public static void Main(string[] args)
{
IntPtr prevInstance = FindWindow(IntPtr.Zero, "This app name"); // this will find also hidden forms
if (prevInstance != IntPtr.Zero)
PostMessage(prevInstance, WM_ACTIVATE, WA_ACTIVE, 0);
else
Application.Run(new ThisApp());
}
 
public ThisApp()
{
loaded = false;
// do initialization here
loaded = true;
}
 
protected override void OnActivated(EventArgs e)
{
if (loaded)
{
// do what you want to do if somebody runs this app again (eg. Visible = true; etc.)
}
 
base.OnActivated(e);
}
 
[DllImport("coredll.dll", SetLastError=true)]
private static extern int PostMessage(IntPtr hWnd, int nMsg, int wParam, int lParam);
 
[DllImport("coredll.dll", SetLastError=true)]
private static extern IntPtr FindWindow(IntPtr wClass, string title);
}
QuestionWhat about notification area??memberRaananan28 Nov '05 - 8:24 
Hi,
I saw the unanswared question and I still needs it. Anyone knows what can be done to show an application that is hidden in the notification area? Is there a way to raise an event on this application and hande it?
 
Thanks
AnswerRe: What about notification area??memberkubben13 Dec '05 - 3:05 
I just posted a solution to this.
 
http://www.codeproject.com/useritems/WindowsAppSingleInstance.asp[^]
 
NOTE this is an un-edit article so it will move.
 
Thanks,
Ben
QuestionNice, butmemberChazsoft7 Oct '05 - 3:18 
:-> I need to do this on a PDA, so how do I do it on Windows CE?? Confused | :confused:
QuestionWhat if?memberSuper Lloyd27 Jun '05 - 1:19 
With stuff like remote desktop you could have multiple user using on different location running on the same PC.
 
thus user A could bring windows of user B and fail it launch on his desktop, if you see what I mean.
 
What do you think of that?
Any work around?.... maybe this new SessionId in 2.0 ?....

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

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130523.1 | Last Updated 1 Oct 2002
Article Copyright 2002 by Marc Clifton
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid