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

相关推荐
v_for_van4 分钟前
C语言__attribute__
服务器·c语言·开发语言·mcu·嵌入式·嵌入式实时数据库
工业一体机老司机27 分钟前
Python实现工业一体机Modbus-TCP通信-从协议解析到多设备轮询实战
开发语言·python·tcp/ip
fpcc33 分钟前
跟我学C++中级篇—static_assert和assert
开发语言·c++
2401_8858850433 分钟前
国际语音php接口代码示例:PHP使用cURL快速调用语音发送API
android·开发语言·前端·人工智能·python·php·语音识别
萌动的小火苗41 分钟前
Linux进程线程面试题【无答案】
linux·运维·服务器·c语言·开发语言
datalover1 小时前
【无标题】
c#·linq
Zenova EdgeOS1 小时前
C++ 工业边缘 Boost.Asio 高级实战
开发语言·c++·边缘计算·工业网关
mqiqe1 小时前
AgentScope Java 2.0 技能仓库(Skill Repository)完全实战指南
java·开发语言·elasticsearch
人工干智能1 小时前
科普:Python中的生成器——带`yield`的函数
开发语言·python
whcyhhh1 小时前
头歌实践教学平台:数据科学与大数据技术导论(十四)
大数据·开发语言·python