C# Winform 已知窗体句柄,如何遍历出所有控件句柄

c# windform 已知窗体句柄,如何遍历出所有控件句柄

复制代码
        public delegate bool CallBack(int hwnd, int lParam);
        public delegate bool EnumWindowsProc(int hWnd, int lParam); 
        List<string> list = new List<string>();

        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool EnumChildWindows(IntPtr hwndParent, EnumWindowsProc lpEnumFunc, IntPtr lParam);
 
        [DllImport("user32.dll")]
        public static extern int GetWindowText(int hWnd, IntPtr lpString, int nMaxCount);
 
        private void toolStripButton5_Click(object sender, EventArgs e)
        {
            list.Clear();
            EnumChildWindows(this.Handle, this.EnumWindowsMethod, IntPtr.Zero);
            //这里得到了所有的子窗口list.Count;
                        //this.Handle改成你已得到的窗体句柄
        }
 
        private bool EnumWindowsMethod(int hWnd, int lParam)
        {
            IntPtr lpString = Marshal.AllocHGlobal(200);
            GetWindowText(hWnd, lpString, 200);//这里获得控件text
            var text = Marshal.PtrToStringAnsi(lpString);
            if (!string.IsNullOrWhiteSpace(text))
                list.Add(text);//添加到list,如果要获得句柄就新建list添加hWnd
            return true;
        }
 

//public delegate bool CallBack(int hwnd, int lParam);
//public delegate bool EnumWindowsProc(int hWnd, int lParam);
//[DllImport("User32.dll", EntryPoint = "FindWindow", SetLastError = false)]
//public static extern int FindWindow(string lpClassName, string lpWindowName);

//[DllImport("user32.dll")]
//[return: MarshalAs(UnmanagedType.Bool)]
//public static extern bool Enumchildwindows(IntPtr hwndParent, EnumWindowsProc lpEnumFunc, IntPtr lParam);
//[DllImport("user32.dll")]
//public static extern int GetWindowText(int hWnd, StringBuilder lpString, int nMaxCount);
//[DllImport("user32.dll")]
//public static extern int EnumThreadWindows(int dwThreadId, CallBack lpfn, int lParam);
//[DllImport("user32.dll")]
//public static extern int EnumWindows(CallBack lpfn, int lParam);
//[DllImport("user32.dll")]
//public static extern int EnumChildWindows(int hWndParent, CallBack lpfn, int lParam);

参考链接:百度安全验证

c#已知窗体句柄,如何遍历出所有控件句柄_微软技术-CSDN问答

相关推荐
天空'之城2 小时前
C 语言工业级通用组件手写 25:简易日志系统
c语言·开发语言·日志系统·嵌入式调试·调试打印
程序喵大人2 小时前
【C++进阶】STL算法与函数对象 -【C++进阶】STL算法与函数对象
开发语言·c++·算法
牛马也想出海2 小时前
使用Playwright被检测为机器人的原因及反检测方案
开发语言·网络·人工智能·机器人·php
明如正午2 小时前
【C#】volatile 关键字深度解析:为什么我的停止按钮有时失灵?
c#
GrowthDiary0072 小时前
Python 常用函数总结
开发语言·python
热心网友俣先生3 小时前
2026年华数杯C 题 超详细解题思路
c语言·开发语言·人工智能
啄缘之间3 小时前
5.1 uvm‑component 的层级结构管理? new (name,parent) 参数
开发语言·笔记·学习·ic·uvm·sv
旖旎夜光3 小时前
C++(类与对象)(下)
开发语言·c++·学习
张小凡vip3 小时前
Python爬虫实战:高效稳定的文件下载模块设计与实现
开发语言·爬虫·python