C#中已经获取了父窗口句柄如何枚举到子窗口的句柄。

2025-04-13 09:13:27
推荐回答(1个)
回答1:

  List list = new List();
        [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;
        }
 
        private bool EnumWindowsMethod(int hWnd, int lParam)
        {
            IntPtr lpString = Marshal.AllocHGlobal(200);
            GetWindowText(hWnd, lpString, 200);
            var text = Marshal.PtrToStringAnsi(lpString);
            if (!string.IsNullOrWhiteSpace(text))
                list.Add(text);
            return true;
        }