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

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

cs 复制代码
    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}");
        }
    }
相关推荐
CoderIsArt8 小时前
参数系统的基类Parameter抽象类
c#
盛夏绽放9 小时前
Python字符串常用方法详解
开发语言·python·c#
Tummer836313 小时前
C#+WPF+prism+materialdesign创建工具主界面框架
开发语言·c#·wpf
ghost14314 小时前
C#学习第23天:面向对象设计模式
开发语言·学习·设计模式·c#
yngsqq15 小时前
(for 循环) VS (LINQ) 性能比拼 ——c#
c#·solr·linq
想做后端的小C15 小时前
C# 面向对象 构造函数带参无参细节解析
开发语言·c#·面向对象
炯哈哈16 小时前
【上位机——WPF】App.xml和Application类简介
xml·开发语言·c#·wpf·上位机
bestcxx16 小时前
c# UTC 时间赋值注意事项
c#·utc
酷炫码神16 小时前
C#运算符
开发语言·c#
zybsjn17 小时前
后端系统做国际化改造,生成多语言包
java·python·c#