【问题标题】:Why is EnumChildWindows skipping children?为什么 EnumChildWindows 会跳过孩子?
【发布时间】:2011-08-10 16:16:41
【问题描述】:

在使用 Windows API 方法 EnumChildWindows 时,我遇到了奇怪的行为。它似乎没有拿起一段儿童窗户。当我使用 Spy++ 向下钻取时,我可以看到孩子,但是当我执行我的代码时,它不会返回我在 Spy++ 中看到的那些。

我在 Spy++ 中看到的 What I see in 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&lt;IntPtr&gt;) 中是否有原因?

【问题讨论】:

  • 我在 FindWindowsByClassAndTitle() 函数中实现了这段代码,它发现窗口的速度比我之前使用的代码快了大约 3000 万倍。

标签: c# winapi


【解决方案1】:

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

“Windows 不会为在调用 EnumChildWindows 之后但在它返回之前创建的任何子窗口调用回调函数。” - Source

上面引用的信息是我头脑中的灯泡。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-06
    • 1970-01-01
    • 1970-01-01
    • 2017-11-10
    • 2015-02-26
    • 1970-01-01
    • 1970-01-01
    • 2014-07-10
    相关资源
    最近更新 更多