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}");
        }
    }
相关推荐
水煮庄周鱼鱼2 小时前
C# 入门简介
开发语言·c#
软件黑马王子3 小时前
Unity游戏制作中的C#基础(6)方法和类的知识点深度剖析
开发语言·游戏·unity·c#
Nicole Potter4 小时前
请说明C#中的List是如何扩容的?
开发语言·面试·c#
gu205 小时前
c#编程:学习Linq,重几个简单示例开始
开发语言·学习·c#·linq
pchmi10 小时前
CNN常用卷积核
深度学习·神经网络·机器学习·cnn·c#
yuanpan10 小时前
23种设计模式之《组合模式(Composite)》在c#中的应用及理解
开发语言·设计模式·c#·组合模式
滴_咕噜咕噜11 小时前
C#基础总结:常用的数据结构
开发语言·数据结构·c#
万兴丶14 小时前
Unity 适用于单机游戏的红点系统(前缀树 | 数据结构 | 设计模式 | 算法 | 含源码)
数据结构·unity·设计模式·c#
程序猿多布16 小时前
C#设计模式 学习笔记
设计模式·c#
软件黑马王子1 天前
Unity游戏制作中的C#基础(5)条件语句和循环语句知识点全解析
游戏·unity·c#