查找同一个进程显示在任务栏上的多个窗口

有的程序可以打开多个窗口并显示在任务栏上。某些情况下,我们需要找到窗口做些事情时,可以参考下面的代码。


    public static class Win32Api
    {
        [DllImport("user32.dll", SetLastError = true)]
        public static extern bool EnumWindows(EnumWindowsProc lpEnumFunc, IntPtr lParam);
        public delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);

        [DllImport("user32.dll", SetLastError = true)]
        public static extern int GetWindowThreadProcessId(IntPtr hWnd, out int lpdwProcessId);

        [DllImport("user32.dll")]
        public static extern bool IsWindowVisible(IntPtr hWnd);
        [DllImport("user32.dll", SetLastError = true)]
        public static extern IntPtr GetWindow(IntPtr hWnd, GetWindow_Cmd uCmd);
        public 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
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            GetWindowCount(Process.GetProcessesByName("myapp")[0]);
        }

        private static void GetWindowCount(Process process)
        {
            int windowCount = 0;
            Thread.Sleep(1000);

            int processId = process.Id;
            Win32Api.EnumWindows((IntPtr hWnd, IntPtr lParam) =>
            {
                int id;
                Win32Api.GetWindowThreadProcessId(hWnd, out id);

                IntPtr parentWindow = Win32Api.GetWindow(hWnd, Win32Api.GetWindow_Cmd.GW_OWNER);
                if (id == processId && parentWindow == IntPtr.Zero && Win32Api.IsWindowVisible(hWnd))
                {
                    windowCount++;
                }
                return true;
            }, IntPtr.Zero);
            Debug.WriteLine($"process window: {windowCount}");
        }
    }

相关推荐

  1. 查找同一个进程显示任务窗口

    2024-04-09 18:42:03       15 阅读
  2. 变量存储同一个地址

    2024-04-09 18:42:03       38 阅读
  3. 服务器用户共享同一个用户目录做法

    2024-04-09 18:42:03       6 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-04-09 18:42:03       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-04-09 18:42:03       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-04-09 18:42:03       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-04-09 18:42:03       18 阅读

热门阅读

  1. Qt 翻译工具:使用 tr() 函数实现多语言支持

    2024-04-09 18:42:03       20 阅读
  2. Vue中Suspense组件详细介绍

    2024-04-09 18:42:03       12 阅读
  3. 特权账号怎么管?企业真的很为难!

    2024-04-09 18:42:03       13 阅读
  4. NIO与BIO

    2024-04-09 18:42:03       11 阅读
  5. 蓝桥杯 算法训练 藏匿的刺客

    2024-04-09 18:42:03       11 阅读
  6. MySQL 常见和不常见的所有查询语句

    2024-04-09 18:42:03       16 阅读
  7. 自己总结的ICT云计算题库三

    2024-04-09 18:42:03       13 阅读