我正在建立一个应用程序,它将得到所有的控制到应用程序winform正在运行。首先,我可以将动态链接库注入到winform正在运行的应用程序中,并获得winform正在运行的应用程序的句柄。在我让所有的子窗口进入应用程序之后。下一步,我想通过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的子窗口中。对不起,我的英语
发布于 2013-04-25 01:12:41
你可以使用下面的代码。将其放入某个辅助类中,例如,像这样使用它...
var hwndChild = EnumAllWindows(hwndTarget, childClassName).FirstOrDefault(); 如果你愿意,你可以“丢掉”class检查--但通常你是在检查一个特定的目标。
你可能还想看看我写的这篇文章--它使用这种方法将焦点设置在远程窗口上(这些情况很常见,你迟早会遇到这个问题)。
Pinvoke SetFocus to a particular control
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<IntPtr> list = gch.Target as List<IntPtr>;
if (list == null)
throw new InvalidCastException("GCHandle Target could not be cast as List<IntPtr>");
list.Add(handle);
return true;
}
public static List<IntPtr> GetChildWindows(IntPtr parent)
{
List<IntPtr> result = new List<IntPtr>();
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<IntPtr> EnumAllWindows(IntPtr hwnd, string childClassName)
{
List<IntPtr> 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;
}
}发布于 2013-04-25 18:06:10
尝试Spy++并查看您尝试枚举的控件是否为窗口。如果它们不是windows,则不能使用此API枚举它们。
https://stackoverflow.com/questions/16196272
复制相似问题