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

标签 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();
        }
    }
}

最佳答案

因此,在 @PaulF、@stuartd@IInspectible 的帮助下,这是我能做到的最好成绩。

Alt-Tab 列表中窗口的顺序大致是窗口的 z 顺序。 @IInspectible 告诉我们,将窗口设置为最顶层会破坏这一点,但在大多数情况下,可以遵守 z 顺序。因此,我们需要获取打开窗口的 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函数中的三个是一个flag:

/// <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 顺序的构建 block ,这(在很大程度上)就是 Alt-Tab 顺序。

关于c# - 检索按 Alt-Tab 列表中的顺序打开的窗口的顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43279386/

相关文章:

git 克隆工作; git 子模块失败 "Permission denied"

c# - 在 C# 中按名称获取 Windows 窗体控件

c# - 使用不存在和连接的 SQL 查询到 LINQ 语法

java - 当设置为父级的标准 IO(命令提示符)时,Windows Java 子进程不输入或输出

java - 没有网络就可以更新吗?

windows-10 - Windows 10 未记录的凭据提供程序 API

c# - 如何将 EF Code First 数据库发布到 Azure

c# - VS Debugger 错了吗?代码: f++抛出的IndexOutOfRangeException

java - 启动 Sikuli 设置时出现问题

windows - 在 powershell 退出时运行脚本