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}");
        }
    }
相关推荐
六bring个六5 小时前
文件压缩处理(一)
开发语言·c#
superman超哥11 小时前
仓颉语言中字符串常用方法的深度剖析与工程实践
开发语言·后端·python·c#·仓颉
bugcome_com11 小时前
C# 中 ref 与 out 参数传递:核心区别与实战解析
c#
用户44884667106012 小时前
.NET 进阶 —— 深入理解线程(3)ThreadPool 与 Task 入门:从手动线程到池化任务的升级
c#·.net
CreasyChan12 小时前
unity四元数 - “处理旋转的大师”
unity·c#·游戏引擎
wuguan_12 小时前
C#索引器
c#·索引器
聪明努力的积极向上12 小时前
【设计】分批查询数据通用方法(基于接口 + 泛型 + 定点复制)
开发语言·设计模式·c#
张人玉13 小时前
C# WPF 折线图制作(可以连接数据库)
数据库·c#·wpf·sugar
kylezhao201914 小时前
C# 中的委托(Delegate)与事件(Event)
c#·c#上位机
lzhdim14 小时前
C#应用程序取得当前目录和退出
开发语言·数据库·microsoft·c#