z474243930 2017-11-30 14:09 采纳率: 33.3%
浏览 5547
已采纳

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

根据网上提供代码,可以用鼠标获取指定窗体句柄,
现在想遍历指定窗体上所有控件的句柄,希望提供代码,
找了一天的帖子了,请勿发参考链接,直接上代码。小白。。。

  • 写回答

3条回答

  • z474243930 2017-12-01 03:46
    关注

    答案出来了:https://zhidao.baidu.com/question/1575352645104568900.html
    说到做到,发代码,链接为源地址,下面我备注一下而已

    
    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;
            }
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 MCNP里如何定义多个源?
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏