由于选项卡顺序的原因,鼠标光标总是得到错误的hwnd-MFC应用程序

Mouse cursor always get the wrong hwnd due to tab order - MFC Application

本文关键字:光标 鼠标 应用程序 hwnd-MFC 错误 于选项 选项 顺序      更新时间:2023-10-16

我试图通过使用鼠标光标获得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;
}

我把鼠标光标放在一个组框中的按钮上,结果总是显示组框的句柄而不是按钮。我发现标签顺序是导致我无法获得按钮的原因

有没有其他方法或其他窗口功能可以用来解决选项卡顺序问题?

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

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