切换到Alt-Tab等上一个活动应用程序

时间:2012-02-27 16:27:37

标签: c# winforms winforms-interop alt-tab

好吧,我发现很多关于通过名称等找到窗口的帖子。我没有找到的是如何找到并将窗口应用程序焦点切换到最后一个活动窗口。我在下面显示的代码将为我提供任务管理器中活动的活动应用程序列表。

我无法弄清楚该怎么做才能弄清楚最后一个活动应用程序是什么应用程序,然后切换到它。例如......

我打开了自定义winform应用程序。

我点击了一个按钮

我的应用程序切换到上一个活动窗口/应用程序。

这是我到目前为止的工作代码。 (这是按钮上的操作,它期望应用程序有一个名为textbox1的文本框。您还需要使用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";
            }
        }         

    }

2 个答案:

答案 0 :(得分:5)

查看此文章:http://www.whitebyte.info/programming/how-to-get-main-window-handle-of-the-last-active-window

具体来说,这段代码:

[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr GetWindow(IntPtr hWnd, uint uCmd);
enum GetWindow_Cmd : uint
{
    GW_HWNDFIRST = 0,
    GW_HWNDLAST = 1,
    GW_HWNDNEXT = 2,
    GW_HWNDPREV = 3,
    GW_OWNER = 4,
    GW_CHILD = 5,
    GW_ENABLEDPOPUP = 6
}
[DllImport("user32.dll", ExactSpelling = true, CharSet = CharSet.Auto)]
public static extern IntPtr GetParent(IntPtr hWnd);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SetForegroundWindow(IntPtr hWnd);

[...]

IntPtr targetHwnd = GetWindow(Process.GetCurrentProcess().MainWindowHandle, (uint)GetWindow_Cmd.GW_HWNDNEXT);
while (true)
{
    IntPtr temp = GetParent(targetHwnd);
    if (temp.Equals(IntPtr.Zero)) break;
    targetHwnd = temp;
}
SetForegroundWindow(targetHwnd);

答案 1 :(得分:2)

由于我的评论没有帮助你,这里有一点简历(虽然没有测试):

[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);
 }