gpt4 book ai didi

c# - 在给定 HWND 的情况下如何获取窗口的子窗口?

转载 作者:太空宇宙 更新时间:2023-11-03 15:08:57 25 4
gpt4 key购买 nike

我有给定窗口的句柄。如何枚举它的子窗口?

最佳答案

Here你有一个可行的解决方案:

public class WindowHandleInfo
{
private delegate bool EnumWindowProc(IntPtr hwnd, IntPtr lParam);

[DllImport("user32")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool EnumChildWindows(IntPtr window, EnumWindowProc callback, IntPtr lParam);

private IntPtr _MainHandle;

public WindowHandleInfo(IntPtr handle)
{
this._MainHandle = handle;
}

public List<IntPtr> GetAllChildHandles()
{
List<IntPtr> childHandles = new List<IntPtr>();

GCHandle gcChildhandlesList = GCHandle.Alloc(childHandles);
IntPtr pointerChildHandlesList = GCHandle.ToIntPtr(gcChildhandlesList);

try
{
EnumWindowProc childProc = new EnumWindowProc(EnumWindow);
EnumChildWindows(this._MainHandle, childProc, pointerChildHandlesList);
}
finally
{
gcChildhandlesList.Free();
}

return childHandles;
}

private bool EnumWindow(IntPtr hWnd, IntPtr lParam)
{
GCHandle gcChildhandlesList = GCHandle.FromIntPtr(lParam);

if (gcChildhandlesList == null || gcChildhandlesList.Target == null)
{
return false;
}

List<IntPtr> childHandles = gcChildhandlesList.Target as List<IntPtr>;
childHandles.Add(hWnd);

return true;
}
}

食用方法:

class Program
{
[DllImport("user32.dll", EntryPoint = "FindWindowEx")]
public static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);

static void Main(string[] args)
{
Process[] anotherApps = Process.GetProcessesByName("AnotherApp");
if (anotherApps.Length == 0) return;
if (anotherApps[0] != null)
{
var allChildWindows = new WindowHandleInfo(anotherApps[0].MainWindowHandle).GetAllChildHandles();
}
}
}

关于c# - 在给定 HWND 的情况下如何获取窗口的子窗口?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42037134/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com