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}");
        }
    }
相关推荐
Macbethad1 小时前
区块链技术在分布式系统中的应用实践技术报告
开发语言·c#
玩泥巴的2 小时前
如何在.NET系统中快速集成飞书任务分配能力
c#·.net·二次开发·飞书
bugcome_com3 小时前
深入理解 C# 特性(Attribute):概念、实现与实战
c#·.net
WebRuntime3 小时前
所有64位WinForm应用都是Chromium浏览器(2)
javascript·c#·.net·web
Sunsets_Red5 小时前
待修改莫队与普通莫队优化
java·c++·python·学习·算法·数学建模·c#
时光追逐者5 小时前
一款基于 .NET 9 构建的企业级 Web RBAC 快速开发框架
前端·c#·.net·.net core
想你依然心痛5 小时前
【TextIn大模型加速器+火山引擎】打造智能文档处理流水线:从跨国药企手册到金融单据核验的全链路实战
金融·c#·火山引擎
kingwebo'sZone5 小时前
win11智能应用控制已阻止此应用
c#
baivfhpwxf20237 小时前
c# 删除文件夹里的所有文件
c#
easyboot7 小时前
python获取C#WEBAPI的数据
开发语言·python·c#