通过FindWindowEx获取所有控件

我正在构建一个应用程序,它将获得所有控件已进入应用程序winform正在运行。 首先,我可以将dll注入应用程序winform正在运行并获取应用程序winform的句柄正在运行。 在我将所有子窗口变为applcation之后。 接下来,我想通过FindWindowEx将所有控件放入子窗口。 但我不能

这是代码:

static ArrayList GetAllChildrenWindowHandles(IntPtr hParent, int maxCount) { ArrayList result = new ArrayList(); int ct = 0; IntPtr prevChild = IntPtr.Zero; IntPtr currChild = IntPtr.Zero; while (true && ct < maxCount) { currChild = FindWindowEx(hParent, prevChild, null, null); if (currChild == IntPtr.Zero) { int errorCode = Marshal.GetLastWin32Error(); break; } result.Add(currChild); prevChild = currChild; ++ct; } return result; } 

我得到一个子窗口的句柄,并使用它是父。 但我无法通过FindWindowEx控制子窗口。 对不起我的英语不好

您可以使用以下代码。 把它放到某个帮助器类中,例如像这样使用它……

 var hwndChild = EnumAllWindows(hwndTarget, childClassName).FirstOrDefault(); 

如果您愿意,您可以“失去” class检查 – 但通常您正在检查特定目标。

您可能还想查看这篇文章我做了一段时间 – 这是使用这种方法将焦点设置在一个远程窗口上(这些场景很常见,你迟早会遇到这个障碍)。
Pinvoke SetFocus到特定的控件

 public delegate bool Win32Callback(IntPtr hwnd, IntPtr lParam); [DllImport("user32.Dll")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool EnumChildWindows(IntPtr parentHandle, Win32Callback callback, IntPtr lParam); [DllImport("user32.dll", CharSet = CharSet.Auto)] static public extern IntPtr GetClassName(IntPtr hWnd, System.Text.StringBuilder lpClassName, int nMaxCount); private static bool EnumWindow(IntPtr handle, IntPtr pointer) { GCHandle gch = GCHandle.FromIntPtr(pointer); List list = gch.Target as List; if (list == null) throw new InvalidCastException("GCHandle Target could not be cast as List"); list.Add(handle); return true; } public static List GetChildWindows(IntPtr parent) { List result = new List(); GCHandle listHandle = GCHandle.Alloc(result); try { Win32Callback childProc = new Win32Callback(EnumWindow); EnumChildWindows(parent, childProc, GCHandle.ToIntPtr(listHandle)); } finally { if (listHandle.IsAllocated) listHandle.Free(); } return result; } public static string GetWinClass(IntPtr hwnd) { if (hwnd == IntPtr.Zero) return null; StringBuilder classname = new StringBuilder(100); IntPtr result = GetClassName(hwnd, classname, classname.Capacity); if (result != IntPtr.Zero) return classname.ToString(); return null; } public static IEnumerable EnumAllWindows(IntPtr hwnd, string childClassName) { List children = GetChildWindows(hwnd); if (children == null) yield break; foreach (IntPtr child in children) { if (GetWinClass(child) == childClassName) yield return child; foreach (var childchild in EnumAllWindows(child, childClassName)) yield return childchild; } } 

尝试使用Spy ++并查看您尝试枚举的控件是否为windows。 如果它们不是Windows,则无法使用此API枚举它们。