Tuesday, February 5, 2013

c# bring another application to foreground

If you ever need to bring another windows process to the foreground or in other words from your code, set focus on another application (not your current running app) and bring it to the front of the screen here is what you need to do:

1) Import the following DLLS:


        [DllImport("user32.dll")]
        public static extern bool ShowWindowAsync(HandleRef hWnd, int nCmdShow);
        [DllImport("user32.dll")]
         public static extern bool SetForegroundWindow(IntPtr WindowHandle);
        public const int SW_RESTORE = 9;


* Don't forget to add the using statement:
       using System.Runtime.InteropServices;

2) Identify the process you want to bring to the front and set the focus on it's window handle:

private void FocusProcess(string procName)
    {
        Process[] objProcesses = System.Diagnostics.Process.GetProcessesByName(procName);        if (objProcesses.Length > 0)
        {
            IntPtr hWnd = IntPtr.Zero;
            hWnd = objProcesses[0].MainWindowHandle;
            ShowWindowAsync(new HandleRef(null,hWnd), SW_RESTORE);
             SetForegroundWindow(objProcesses[0].MainWindowHandle);
        }
    }







13 comments:

  1. Thank you, I have used this method with success.

    ReplyDelete
  2. Thank you, it works great !!!

    Kochav

    ReplyDelete
  3. Love you buddy. The only code which works like a charm.

    ReplyDelete
  4. I want to give the focus to the last active (focused) application (whichever it is, for example Notepad, Chrome).. How can I do that?

    ReplyDelete
  5. Thanks. Very Helpful.

    ReplyDelete
  6. Not working for me. How to Identify the process I want?

    ReplyDelete
    Replies
    1. Oh. Now It's working. I was puting the process name with the .exe

      Thank Buddy...

      Delete
  7. 6 years later, and this is still a great help. Thanks

    ReplyDelete
  8. Thanks. This saved me.

    ReplyDelete
  9. Thankyou. I adapted to use GetProcessById and it works wonderfully.

    ReplyDelete
  10. thank you it's work with notepad , but I tried to focus chrome not working.

    ReplyDelete