4

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

我不知道该怎么做是找出最后一个活动应用程序是哪个应用程序,然后切换到它。例如...

我打开了我的自定义 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";
            }
        }         

    }
4

2 回答 2

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);
于 2012-02-27T16:59:54.263 回答
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);
 }
于 2012-02-27T17:05:57.847 回答