Qt with WinAPI MouseProc

Qt with WinAPI MouseProc

本文关键字:MouseProc WinAPI with Qt      更新时间:2023-10-16

我需要跟踪屏幕上的光标位置,为此我使用 WinAPI 中的函数

// code from Qt(!) project
#include <windows.h>
#pragma comment(lib, "user32.lib")
MyClass *myclass;
static HHOOK hHook;
LRESULT CALLBACK MouseProc(int nCode, WPARAM wParam, LPARAM lParam) {   
switch( wParam )
{
case WM_MOUSEMOVE:
POINT p;
GetCursorPos(&p);                   
myclass->setState(QPoint(p.x,p.y),myclass->getParent()); // setCursor
break;
}
return CallNextHookEx(hHook, nCode, wParam, lParam);
}
//in the class constructor
hHook = (HHOOK) ::SetWindowsHookEx(WH_MOUSE_LL, (HOOKPROC)MouseProc, GetModuleHandle(0),0) ;

这有效,但有时程序在退出时崩溃。如果注释掉最后一行,程序永远不会崩溃,但不会跟踪鼠标。我不知道WinApi,所以错误可能很明显

编辑 1:

我知道如何获取坐标,但问题是如果使用 WinAPI 退出后程序崩溃

编辑2: 谢谢Nurav,错误是它,单击后我删除了应用程序,如果移动鼠标,将调用此函数,其中我指的是窗口的子项

您可以使用GetCursorPos()功能:

LRESULT CALLBACK MouseProc(int nCode, WPARAM wParam, LPARAM lParam) {
switch(wParam)
{
case WM_MOUSEMOVE:
POINT p;
GetCursorPos(&p);
sprintf(msgbuf, "My coordinates is (%d,%d)n", p.x,p.y);
OutputDebugString(msgbuf);
break;
}
}

您可以在此处阅读有关它的更多信息。 编辑 1:

如果是自己的win32窗口,这是一个可行的解决方案。但如果是另一个窗口,你就不能使用它!