我试图通过使用鼠标光标获取在MFC应用程序中开发的窗口句柄并将其打印出来。

这是我用来获取窗口句柄的代码。

#include<windows.h>
#include<iostream>
using namespace std;

int main() {

        POINT pt;
        Sleep(5000);
        GetCursorPos(&pt);
        SetCursorPos(pt.x,pt.y);
        Sleep(100);

        HWND hPointWnd = WindowFromPoint(pt);
        SendMessage(hPointWnd, WM_LBUTTONDOWN, MK_LBUTTON,MAKELONG(pt.x,pt.y));
        SendMessage(hPointWnd, WM_LBUTTONUP, 0, MAKELONG(pt.x,pt.y));

        char class_name[100];
        char title[100];
        GetClassNameA(hPointWnd,class_name, sizeof(class_name));
        GetWindowTextA(hPointWnd,title,sizeof(title));
        cout <<"Window name : "<<title<<endl;
        cout <<"Class name  : "<<class_name<<endl;
        cout <<"hwnd        : " <<hPointWnd<<endl<<endl;

        system("PAUSE");
        return 0;

}


我将鼠标光标放在分组框内的按钮上,然后结果总是向我显示分组框的句柄而不是按钮。我发现选项卡顺序是导致我无法获得按钮手柄的原因

还有其他方法或其他Windows功能可用于解决制表符顺序问题吗?

任何帮助将不胜感激。非常感谢!

最佳答案

首先,您需要调用WindowFromPoint以获得最大程度嵌套的窗口句柄,然后需要调用RealChildWindowFromPoint以获得“真实的”窗口并避免使用组框。但这也避免了静态文本,因此您需要继续使用ChildWindowFromPointExCWP_ALL标志查找子窗口。

实现将是这样的:

POINT pt;
GetCursorPos(&pt);
// Get the window from point
HWND hWnd = WindowFromPoint(pt);
// map cursor position to window's client coordinates
MapWindowPoints(NULL, hWnd, &pt, 1);

while (true)
{
    // Now let's look for real child window
    HWND hWndChild = RealChildWindowFromPoint(hWnd, pt);
    if (hWndChild == hWnd)
    {
        // There's no "real" child but we still need to look
        // for Disabled/Transparent/Invisible windows
        hWndChild = ChildWindowFromPointEx(hWnd, pt, CWP_ALL);
    }

    if (hWndChild == NULL || hWndChild == hWnd)
        break; // we haven't found any child, stop search

    // Continue search within child window
    MapWindowPoints(hWnd, hWndChild, &pt, 1);
    hWnd = hWndChild;
}

// At this point hWnd variable should contain the handle that you're looking for

10-08 11:41