c++ - 由于 Tab 键顺序,鼠标光标总是得到错误的 hwnd - MFC 应用程序

标签 c++ mfc groupbox hwnd mouse-cursor

我尝试使用鼠标光标获取在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;

}

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

是否有任何其他方法或其他窗口功能可用于解决 Tab 键顺序问题?

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

最佳答案

首先您需要调用 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

关于c++ - 由于 Tab 键顺序,鼠标光标总是得到错误的 hwnd - MFC 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58839523/

相关文章:

c++ - 为什么 Windres 在我的 GROUPBOX 语句中报告语法错误?

c# - 使用视觉状态时 GroupBox 标题背景不更新

WPF - Groupbox 标题对齐

C++ 和 Boost XML 存档(序列化): Can I specify the tag name for elements?(默认值: "item")

c++ - 如何使用 boost::random_device 生成密码安全的 64 位整数?

c++ - 求和巨大的数字

winapi - 在 Win32 应用程序中捕获 SHIFT + TAB 和仅按 TAB 按钮

c++ - 如何在不使用 std::vectors 的情况下使用运算符 -= 从动态分配的对象数组中删除元素?

visual-c++ - 在MFC,VC++,多线程应用程序上挂起/随机崩溃

c++ - MFC加载资源时如何确定默认语言ID?