如何获得具有HWND的窗口的子窗口?

时间:2009-09-01 15:39:20

标签: c# windows winapi children

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

5 个答案:

答案 0 :(得分:21)

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();
        }
    }
}

答案 1 :(得分:11)

使用:

internal delegate int WindowEnumProc(IntPtr hwnd, IntPtr lparam);

[DllImport("user32.dll")]
internal static extern bool EnumChildWindows(IntPtr hwnd, WindowEnumProc func, IntPtr lParam);

您将获得传入函数的回调。

答案 2 :(得分:7)

我找到了Managed WindowsAPI的最佳解决方案。它有一个可用于选择窗口的CrossHair控件(不是问题的一部分),以及一个方法AllChildWindows可以获取可能包含EnumChildWindows函数的所有子窗口。最好不要重新发明轮子。

答案 3 :(得分:6)

使用带有p / invoke的EnumChildWindows。以下是关于其中某些行为的有趣链接:https://blogs.msdn.microsoft.com/oldnewthing/20070116-04/?p=28393

如果您不知道窗口的句柄,只知道它的标题,则需要使用EnumWindows。 http://pinvoke.net/default.aspx/user32/EnumWindows.html

答案 4 :(得分:3)

以下是EnumWindows的托管替代方法,但您仍需要使用EnumChildWindows来查找子窗口的句柄。

foreach (Process process in Process.GetProcesses())
{
   if (process.MainWindowTitle == "Title to find")
   {
      IntPtr handle = process.MainWindowHandle;

      // Use EnumChildWindows on handle ...
   }
}