为什么 EnumChildWindows 跳过了子窗口?

10

使用Windows API方法EnumChildWindows时,我发现它会出现奇怪的行为。它似乎无法捕获一组子窗口。当我使用Spy++进行深入分析时,我可以看到这些子窗口,但是当我执行我的代码时,它不会返回我在Spy++中看到的那些子窗口。

Spy++中的情况 Spy++中的情况 http://img24.imageshack.us/img24/9264/spyhandles.png

这是我的代码:

public delegate bool EnumWindowProc(IntPtr hWnd, IntPtr parameter);

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

    public static List<IntPtr> GetChildWindows(IntPtr parent)
    {
        List<IntPtr> result = new List<IntPtr>();
        GCHandle listHandle = GCHandle.Alloc(result);
        try
        {
            EnumWindowProc childProc = new EnumWindowProc(EnumWindow);
            EnumChildWindows(parent, childProc, GCHandle.ToIntPtr(listHandle));
        }
        finally
        {
            if (listHandle.IsAllocated)
                listHandle.Free();
        }
        return result;
    }

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

我调用 EnumChildWindows 方法时,为什么截图中突出显示的红色部分不会被填充到我的集合 (List<IntPtr>) 中?


我在我的FindWindowsByClassAndTitle()函数中实现了这段代码,它的速度比我之前使用的代码快了大约3000万倍。 - Anders
1个回答

8

糟糕!我发现了我的错误。之所以我只得到一半的子窗口,是因为我没有等待足够长的时间让窗口最初加载并创建其中所有的子窗口,因此我只得到了在调用获取所有子窗口的函数时它创建的前半部分。因此,在调用EnumChildWindows()之前,我添加了一行代码来睡眠。

"在调用EnumChildWindows之后但在其返回之前创建的任何子窗口都不会导致Windows调用回调函数。" - 来源

上述引用的信息点亮了我的思路。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接