![](/img/trans.png)
[英]Can I always be sure of the hierarchical order of controls found via FindWindowEx?
[英]get all controls by FindWindowEx
我正在構建一個應用程序,它將使所有控件都進入應用程序winform運行中。 首先,我可以將dll注入正在運行的應用程序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將所有控件放到子窗口中。 對不起我的英語不好
您可以使用下面的代碼。 將它放在某個地方的幫助器類中,例如像這樣使用它...
var hwndChild = EnumAllWindows(hwndTarget, childClassName).FirstOrDefault();
您可以根據需要“丟失” class
檢查-但通常是在檢查特定目標。
您可能還想檢查一下我寫的一則文章-使用此方法將焦點設置在遠程窗口上(這些情況非常普遍,您遲早會遇到這種麻煩)。
將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<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;
}
}
嘗試使用Spy ++,然后查看要枚舉的控件是否為Windows。 如果它們不是Windows,則無法使用此API枚舉它們。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.