Thursday, January 18, 2007

Programmatically Switch to Another Running Application/Process

Question
In my Windows application, I want to be able to switch to another application running on my computer. For example, I want to switch to Internet Explorer and make it the active window. How do I do that?

Answer
To solve this problem, you need to first obtain the list of processes currently running on your system. You then need to find the required application/process to switch to and then make that window active.

First, import the following namespace:

using System.Diagnostics;

Then, declare the following functions from the user32.dll (yes, you will use P/Invoke to switch the current active window):

    public partial class Form1 : Form
    {
        [DllImport("user32.dll")]
           private static extern bool
           SetForegroundWindow(IntPtr hWnd);

        [DllImport("user32.dll")]
           private static extern bool ShowWindowAsync(
           IntPtr hWnd, int nCmdShow);

Define the following constant:

        private const int SW_RESTORE = 9;
     
Assuming that you want to switch to IE, the following function will retrieve the list of processes running, look for IE, and then make it the active window:

        private void SwitchToIE()
        {
            Process[] procs = Process.GetProcesses();
            if (procs.Length != 0)
            {
                for (int i = 0; i < procs.Length; i++)
                {
                    try
                    {
                        if (procs[i].MainModule.ModuleName ==
                           "IEXPLORE.EXE")
                        {
                            IntPtr hwnd =
                               procs[i].MainWindowHandle;
                            ShowWindowAsync(hwnd, SW_RESTORE);
                            SetForegroundWindow(hwnd);
                            return;
                        }
                    }
                    catch
                    {
                    }
                }
            }
            else
            {
                MessageBox.Show("No process running");
                return;
            }
            MessageBox.Show(
               "Internet Explorer is not running");
        }

Voila! If at least one instance of IE is running, you will be able to switch to it; else it will display the message “Internet Explorer is not running”.

4 comments:

Deepak said...

Thanks for this code.
It help us a lot. I am quite unaware of the system programming. Can you please let me know from where we can get all this details for the system programming?
Like what else the user32.dll can do?

Dermot said...

Thanks! Needed this :-)

lok pan Wong said...

the code is miss
using System.Runtime.InteropServices;

for the DllImport

lok pan Wong said...

using System.Runtime.InteropServices;

is missing