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}");
        }
    }
相关推荐
雪隐19 小时前
WPF + MVVM 实战系列01-一个老狗回炉重造 WPF 的 12 天血泪史
sqlite·c#·mvvm
在世修行20 小时前
从零打造 C# 工业视觉检测系统(四):海康威视 MVS SDK 入门与相机枚举实战
数码相机·c#·视觉检测
神秘的MT21 小时前
C# WinForm Socket 服务器 + 串口转发
服务器·网络·学习·c#
czhc11400756631 天前
8.4:今日概念与语法总结
c#
大数据张老师1 天前
Typora 导出 Word 模版操作手册
开发语言·c#·word·typora
我是苏苏1 天前
C#基础:使用System.Speech.Synthesis离线播放/朗读文字内容
开发语言·c#
程序员-Benothing1 天前
如何实现高并发系统订单30分钟自动关闭?
开发语言·c#·wpf
海盗12342 天前
微软技术周报 ——2026-08-03
后端·python·microsoft·c#·.netcore
dalong102 天前
WPF:3D甜甜圈
3d·c#·wpf·甜甜圈
神秘的MT2 天前
C# WinForm Socket 类 常用方法 (C# .NET,TCP 场景)
服务器·网络·学习·tcp/ip·c#·winform