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

相关推荐
代码村新手14 分钟前
C++-类和对象(中)
java·开发语言·c++
葵花楹31 分钟前
【JAVA课设】【游戏社交系统】
java·开发语言·游戏
kylezhao201934 分钟前
C# 文件的输入与输出(I/O)详解
java·算法·c#
赵谨言42 分钟前
Python串口的三相交流电机控制系统研究
大数据·开发语言·经验分享·python
民乐团扒谱机1 小时前
【微实验】数模美赛备赛:多目标优化求解实战(MATLAB实现,以流水车间调度为例)
开发语言·数学建模·matlab·甘特图·遗传算法·多目标优化·优化模型
努力的小陈^O^1 小时前
问题:Spring循环依赖问题排查与解决
java·开发语言·前端
Ccjf酷儿1 小时前
C++语言程序设计 (郑莉)第十章 泛型程序设计与C++标准模板库
开发语言·c++
kylezhao20192 小时前
C# TreeView 控件详解与应用
c#
FreeBuf_2 小时前
利用零宽度字符的隐形JavaScript混淆工具InvisibleJS浮出水面
开发语言·javascript·ecmascript
lsx2024062 小时前
Go 语言指针
开发语言