C#通过名称和序号使用FindWindowEx获取子句柄

时间:2011-04-15 06:24:29

标签: c# winapi visual-c++ handle spy++

根据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”控件的任何句柄?事实是,按钮标题可能会有所不同,因此我无法通过名称定义第四个参数直接找到它们。

1 个答案:

答案 0 :(得分:14)

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++