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}");
        }
    }
相关推荐
asdzx6716 小时前
使用 Python 精准操控 Word 字体:获取与替换方案
python·c#·word
逝水无殇18 小时前
C# 特性详解
开发语言·后端·c#
LongtengGensSupreme18 小时前
C#图像内存高速拷贝:使用Marshal.AllocHGlobal与ArrayPool实现内存拷贝的几个方法
开发语言·数码相机·c#
影寂ldy20 小时前
C# 五大加密算法全套实战(AES/DES对称、RSA非对称、MD5/SHA256哈希)
开发语言·c#·哈希算法
互联网底层民工20 小时前
异步 / 多线程并发(高频八股 · 详解版)
c#
逝水无殇21 小时前
C# 反射详解
开发语言·后端·c#
神秘的MT21 小时前
SQL Server 分页查询 ROW_NUMBER () OFFSET...FETCH游标(Cursor) 数据插入
数据库·sql·学习·c#·winform
我才是银古21 小时前
一个人写出的 3D 几何引擎:Ara3D SDK 技术深度剖析
c#·三维几何·ai平台
逝水无殇1 天前
C# 异常处理详解
开发语言·后端·c#