按照Alt-Tab列表中的顺序检索打开窗口的顺序?

时间:2017-04-07 13:27:08

标签: c# windows windows-10 system.diagnostics

这是我的C#应用​​程序的完整代码,目标很简单。我想检索系统上打开的窗口,按照最近打开的方式排序,就像在Alt-Tab列表中一样。 Alt-Tab列表列出了上次打开的程序,以便按Alt-Tab并仅释放一次将返回到您打开的最后一个窗口。此代码适用于Windows 10.下面的代码确实获取了我需要的信息,但顺序不正确。我应该在哪里寻找我需要的信息?

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace GetOpenWindowName
{
    class Program
    {
        static void Main(string[] args)
        {
            Process[] processlist = Process.GetProcesses();

            foreach (Process process in processlist)
            {
                if (!String.IsNullOrEmpty(process.MainWindowTitle))
                {
                    Console.WriteLine("Process: {0} ID: {1} Window title: {2}", process.ProcessName, process.Id, process.MainWindowTitle);
                }
            }

            Console.ReadLine();
        }
    }
}

2 个答案:

答案 0 :(得分:2)

所以,在 @PaulF,@ stuartd, @IInspectible。

的帮助下,这是我能做的最好的事情。

Alt-Tab列表中窗口的顺序大致是窗口的z顺序。 @IInspectible 告诉我们,设置为最顶层的窗口会破坏这一点,但在大多数情况下,z-order可以被尊重。所以,我们需要获得打开窗口的z顺序。

首先,我们需要引入外部函数GetWindow,使用以下两行:

[DllImport("user32.dll", SetLastError = true)]
private static extern IntPtr GetWindow(IntPtr hWnd, int nIndex);

一旦该函数存在,我们就可以创建这个函数来获得z顺序:

public static int GetZOrder(Process p)
{
    IntPtr hWnd = p.MainWindowHandle;
    var z = 0;
    // 3 is GetWindowType.GW_HWNDPREV
    for (var h = hWnd; h != IntPtr.Zero; h = GetWindow(h, 3)) z++;
    return z;
}

关键点:GetWindow函数调用中的三个是一个标志:

/// <summary>
/// The retrieved handle identifies the window above the specified window in the Z order.
/// <para />
/// If the specified window is a topmost window, the handle identifies a topmost window.
/// If the specified window is a top-level window, the handle identifies a top-level window.
/// If the specified window is a child window, the handle identifies a sibling window.
/// </summary>
GW_HWNDPREV = 3,

这些是从进程列表中查找窗口的z顺序的构建块,这是(大多数情况下)Alt-Tab顺序的内容。

答案 1 :(得分:2)

实施EnumWindows似乎会以Tab键顺序返回窗口

[DllImport("user32.dll")]
private static extern bool EnumWindows(EnumWindowsProc enumProc, IntPtr lParam);

这里很好地解释了如何使用 How can I use EnumWindows to find windows with a specific caption/title?