Search code examples
c#winformswinforms-interopalt-tab

Switch to last active application like Alt-Tab


ok, I have found many posts on finding a window by name, etc. What I have not found is how to find and switch the window application focus to last active window. The code I am showing below will give me the list of active applications in the task manager that are active.

What I can not figure out how to do is figure out what application was the last active application, and then switch to it. for example...

I have my custom winform application open.

I click a button

My application switches to the last active window / application.

Here is the working code I have so far. (this is the action on a button, and it expects that the application has a textbox named textbox1. you will also need to add using System.Diagnostics;

    private void button1_Click(object sender, EventArgs e)
    {

        Process[] procs = Process.GetProcesses();
        IntPtr hWnd;
        foreach (Process proc in procs)
        {
            if ((hWnd = proc.MainWindowHandle) != IntPtr.Zero)
            {
                textBox1.Text += (proc.ProcessName.ToString());
                textBox1.Text += "\t";
                textBox1.Text += (hWnd.ToString());
                textBox1.Text += "\r\n";
            }
        }         

    }

Solution

  • Since my comments didn't help you, here's a little resume (didn't test it though):

    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    static extern bool IsWindowVisible(IntPtr hWnd);
    
    [DllImport("user32.dll")]
    static extern IntPtr GetLastActivePopup(IntPtr hWnd);
    
    [DllImport("user32.dll", ExactSpelling = true)]
    static extern IntPtr GetForegroundWindow();
    
    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    static extern bool SetForegroundWindow(IntPtr hWnd);
    
    const uint GA_PARENT = 1;
    const uint GA_ROOT = 2;
    const uint GA_ROOTOWNER = 3;
    
    public IntPtr GetPreviousWindow()
    {
            IntPtr activeAppWindow = GetForegroundWindow();
            if ( activeAppWindow == IntPtr.Zero )
                return IntPtr.Zero;
    
            IntPtr prevAppWindow = GetLastActivePopup(activeAppWindow);
            return IsWindowVisible(prevAppWindow) ? prevAppWindow : IntPtr.Zero;
     }
    
     public void FocusToPreviousWindow()
     {
         IntPtr prevWindow = GetPreviousWindow();
         if (  prevWindow != IntPtr.Zero )
             SetForegroundWindow(prevWindow);
     }