2011-08-10 61 views
10

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

我在间谍++ 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; 
    } 

是否有一个原因,为什么在上面的截图中的红色突出部分就不会得到填充到我的收藏( List<IntPtr>)当调用EnumChildWindows?

+0

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

回答

8

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

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

上面引用的那条信息就是把灯泡放在我头上的东西。