C#使用FindWindowEx按名称和序号进行子句柄处理

根据http://msdn.microsoft.com/en-us/library/ms633500(v=vs.85).aspx我定义了FindWindowEx函数。

using System.Runtime.InteropServices; [DllImport("user32.dll", CharSet=CharSet.Unicode)] static extern IntPtr FindWindowEx(IntPtr parentHandle, IntPtr childAfter, string lclassName, string windowTitle); 

现在我能够找到第一个 “Button”控件的句柄(从Spy ++获取名称),将childAfter设置为IntPtr.Zero

 IntPtr hWndParent = new IntPtr(2032496); // providing parent window handle IntPtr hWndButton = FindWindowEx(hWndParent, IntPtr.Zero, "Button", string.Empty); 

如何在父窗口中获取“Button”控件的第二个第三个或任何句柄? 事实是,按钮标题可能会有所不同,所以我无法通过名称定义第四个参数直接找到它们。

 static IntPtr FindWindowByIndex(IntPtr hWndParent, int index) { if (index == 0) return hWndParent; else { int ct = 0; IntPtr result = IntPtr.Zero; do { result = FindWindowEx(hWndParent, result, "Button", null); if (result != IntPtr.Zero) ++ct; } while (ct < index && result != IntPtr.Zero); return result; } } 

使用如下:

 IntPtr hWndThirdButton = FindWindowByIndex(hWnd, 3); // handle of third "Button" as shown in Spy++