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问答

相关推荐
侃侃_天下5 小时前
最终的信号类
开发语言·c++·算法
echoarts5 小时前
Rayon Rust中的数据并行库入门教程
开发语言·其他·算法·rust
Aomnitrix6 小时前
知识管理新范式——cpolar+Wiki.js打造企业级分布式知识库
开发语言·javascript·分布式
大飞pkz6 小时前
【设计模式】C#反射实现抽象工厂模式
设计模式·c#·抽象工厂模式·c#反射·c#反射实现抽象工厂模式
每天回答3个问题6 小时前
UE5C++编译遇到MSB3073
开发语言·c++·ue5
伍哥的传说6 小时前
Vite Plugin PWA – 零配置构建现代渐进式Web应用
开发语言·前端·javascript·web app·pwa·service worker·workbox
小莞尔7 小时前
【51单片机】【protues仿真】 基于51单片机八路抢答器系统
c语言·开发语言·单片机·嵌入式硬件·51单片机
我是菜鸟0713号7 小时前
Qt 中 OPC UA 通讯实战
开发语言·qt
JCBP_7 小时前
QT(4)
开发语言·汇编·c++·qt·算法
Brookty7 小时前
【JavaEE】线程安全-内存可见性、指令全排序
java·开发语言·后端·java-ee·线程安全·内存可见性·指令重排序