Home > C# How To, C# Snippets, Development > C# Check If Application Is Already Running Then Set Focus

C# Check If Application Is Already Running Then Set Focus

October 6th, 2011

Here is a simple code snippet to assist in determining if another instance of the application is running. If there is another instance then close the current one and provide focus to the already running process.

I located this code on a forum, link here

Code Snippet:

    using System;
    using System.Diagnostics;
    using System.Runtime.InteropServices;

    /// -------------------------------------------------------------------------------------------------
    /// <summary> Application Running Helper. </summary>
    /// -------------------------------------------------------------------------------------------------
    public static class ApplicationRunningHelper
    {
        [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);

        /// -------------------------------------------------------------------------------------------------
        /// <summary> check if current process already running. if running, set focus to existing process and 
        ///           returns <see langword="true"/> otherwise returns <see langword="false"/>. </summary>
        /// <returns> <see langword="true"/> if it succeeds, <see langword="false"/> if it fails. </returns>
        /// -------------------------------------------------------------------------------------------------
        public static bool AlreadyRunning()
        {
            /*
            const int SW_HIDE = 0;
            const int SW_SHOWNORMAL = 1;
            const int SW_SHOWMINIMIZED = 2;
            const int SW_SHOWMAXIMIZED = 3;
            const int SW_SHOWNOACTIVATE = 4;
            const int SW_RESTORE = 9;
            const int SW_SHOWDEFAULT = 10;
            */
            const int swRestore = 9;

            var me = Process.GetCurrentProcess();
            var arrProcesses = Process.GetProcessesByName(me.ProcessName);

            if (arrProcesses.Length > 1)
            {
                for (var i = 0; i < arrProcesses.Length; i++)
                {
                    if (arrProcesses[i].Id != me.Id)
                    {
                        // get the window handle
                        IntPtr hWnd = arrProcesses[i].MainWindowHandle;

                        // if iconic, we need to restore the window
                        if (IsIconic(hWnd))
                        {
                            ShowWindowAsync(hWnd, swRestore);
                        }

                        // bring it to the foreground
                        SetForegroundWindow(hWnd);
                        break;
                    }
                }
                return true;
            }

            return false;
        }
    }

To implement this run this code in your program.cs

    /// -------------------------------------------------------------------------------------------------
    /// <summary> Main Program Entry Class. </summary>
    /// -------------------------------------------------------------------------------------------------
    public static class Program
    {
        /// -------------------------------------------------------------------------------------------------
        /// <summary> The main entry point for the application. </summary>
        /// -------------------------------------------------------------------------------------------------
        [STAThread]
        public static void Main()
        {
            if (ApplicationRunningHelper.AlreadyRunning())
            {
                return;
            }

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new SysTray());
        }
    }
  1. Clive
    January 23rd, 2012 at 09:35 | #1

    Clear and to the point, thanks!

  2. Ashish Pandey
    February 26th, 2012 at 00:43 | #2

    Very nice article. I really enjoyed it reading. And it also cleared lot of my doubts about running process in c#. Check this link too its also having nice post with wonderful explanation on Checking process in C#.

    http://www.mindstick.com/Articles/c5c08a18-908c-4410-925b-a4f57e62e1c7/?RUNNING%20PROCESS%20IN%20C#

    Thanks Everyone for your precious post.

  3. Driver
    July 5th, 2012 at 06:32 | #3

    It works beautifully, thank you very much… I had sought it very long time. I am very excited. It works exactly the way I want. Super!

  4. Driver
    July 5th, 2012 at 07:29 | #4

    I tried truncate some code and it works also well.

    using System.Diagnostics;
    using System.Windows.Forms;

    class OneInstanceWindow : Form
    {
    //your Fields, Methods, Properties, …

    [System.Runtime.InteropServices.DllImport(“user32.dll”)]
    static extern bool SetForegroundWindow(System.IntPtr mwh);

    static void Main()
    {
    var me = Process.GetCurrentProcess();
    var arrProcesses = Process.GetProcessesByName(me.ProcessName);

    for (var i = 0; i < arrProcesses.Length; i++) {
    if (arrProcesses[i].Id != me.Id) {
    SetForegroundWindow(arrProcesses[i].MainWindowHandle);
    return;
    }
    }
    Application.Run(new OneInstanceWindow());
    }
    }

    It could be main-window template for the creation of all windows applications. 😉

  5. Driver
    July 5th, 2012 at 07:35 | #5

    I tried truncate some code and it works also well.

    using System.Diagnostics;
    using System.Windows.Forms;

    class OneInstanceWindow : Form
    {
    //your Fields, Methods, Properties, …

    [System.Runtime.InteropServices.DllImport(“user32.dll”)]
    static extern bool SetForegroundWindow(System.IntPtr mwh);

    static void Main()
    {
    var me = Process.GetCurrentProcess();
    var arrProcesses = Process.GetProcessesByName(me.ProcessName);

    for (var i = 0; i < arrProcesses.Length; i++) {
    if (arrProcesses[i].Id != me.Id) {
    SetForegroundWindow(arrProcesses[i].MainWindowHandle);
    return;
    }
    }
    Application.Run(new OneInstanceWindow());
    }
    }

    It could be main-window template for the creation of all windows applications. 😉

  6. July 29th, 2013 at 11:25 | #6

    Thanks for this piece of useful code.. I was having issues getting this to work on one of my apps. This code worked very well… thank you.

  7. Sarang
    November 28th, 2013 at 16:21 | #7

    Perfect! Thank you so much..

  8. Mike
    February 20th, 2014 at 14:49 | #8

    I had an interesting problem with this code. If I have multiple users logged in to the same PC, only the first user was able to run my exe. The code to detect if an application is already running is too good! It detects the application running from other users on the same machine.

    To easily fix the problem, change:

    if (arrProcesses[i].Id != me.Id)

    to

    if (arrProcesses[i].Id != me.Id && arrProcess[i].SessionId == me.SessionId)

    • April 3rd, 2014 at 00:09 | #9

      Mike,

      Thank You for the suggestion.

      Cheers
      Dan

Comments are closed.
%d bloggers like this: