我正在尝试获取全局鼠标位置。我有一个可以获取鼠标位置的钩子,但是它只能在钩子代码中访问它。试图访问 main 中的数据是行不通的。
解释这一点的最好方法是使用代码:
LRESULT CALLBACK mouseHookProc(int nCode, WPARAM wParam, LPARAM lParam)
{
PMSLLHOOKSTRUCT p = (PMSLLHOOKSTRUCT) lParam;
position.x = p->pt.x;
position.y = p->pt.y;
std::cout<<position.x<<std::endl;
return CallNextHookEx(NULL, nCode, wParam, lParam);
}
int WINAPI WinMain (HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpszArgument,int nCmdShow)
{
HHOOK mouseHook = SetWindowsHookEx(WH_MOUSE_LL,mouseHookProc,hInstance,NULL);
MessageBox(NULL, "Press OK to close.", "", MB_OK);
return 0;
}
使用上面的代码,移动鼠标将在控制台窗口中显示新的位置。但是,如果我把std::cout<<position.x<<std::endl;
main 放在里面,它只会说 0. position
是一个全局变量。
输出在 main 内部时的代码:
LRESULT CALLBACK mouseHookProc(int nCode, WPARAM wParam, LPARAM lParam)
{
PMSLLHOOKSTRUCT p = (PMSLLHOOKSTRUCT) lParam;
position.x = p->pt.x;
position.y = p->pt.y;
return CallNextHookEx(NULL, nCode, wParam, lParam);
}
int WINAPI WinMain (HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpszArgument,int nCmdShow)
{
HHOOK mouseHook = SetWindowsHookEx(WH_MOUSE_LL,mouseHookProc,hInstance,NULL);
for(;;)
{
std::cout<<position.x<<std::endl;
}
MessageBox(NULL, "Press OK to close.", "", MB_OK);
return 0;
}
第一段代码工作正常,它检测到鼠标位置,我只是不知道如何将 x,y 数据放入我的 main 中。