我编写了一个小的全局钩子,可以处理键盘和鼠标输入。我希望能够在鼠标移动时输出击键但到目前为止我无法将击键发送到任何顶级窗口。我唯一能想到的就是我的位是正确的,因为PostMessage()的lParam是正确的但是我已经阅读了文档,看起来这应该是正确的顺序。我已经在记事本,Chrome,微软词和其他一些程序中尝试过它,并且我们已经能够让它工作,所以我迷失了。
这是我到目前为止所拥有的
HHOOK hMouseHook;
MOUSEHOOKSTRUCT previousMouseEventData;
int main(int argc, char** argv)
{
HANDLE hThread;
DWORD dwThread;
hThread = CreateThread(NULL, NULL, (LPTHREAD_START_ROUTINE)setHooks, (LPVOID)argv[0], NULL, &dwThread);
if (hThread)
return WaitForSingleObject(hThread, INFINITE);
}
DWORD WINAPI setHooks(LPVOID lpParm)
{
HINSTANCE hInstance = GetModuleHandle(NULL);
if (!hInstance)
hInstance = LoadLibrary((LPCWSTR)lpParm);
if (!hInstance)
return -1;
hMouseHook = SetWindowsHookEx(WH_MOUSE_LL, (HOOKPROC)MouseEvent, hInstance, NULL);
MessageLoop();
UnhookWindowsHookEx(hMouseHook);
return 0;
}
void MessageLoop()
{
MSG message;
while (GetMessage(&message, NULL, 0, 0))
{
TranslateMessage(&message);
DispatchMessage(&message);
}
}
- 据我所知,这应该有效
_declspec(dllexport) LRESULT CALLBACK MouseEvent(int nCode, WPARAM wParam, LPARAM lParam)
{
if (nCode == HC_ACTION)
{
try {
MOUSEHOOKSTRUCT newMouseEventData = *(MOUSEHOOKSTRUCT*)lParam;
if (newMouseEventData.hwnd == previousMouseEventData.hwnd &&
newMouseEventData.pt.x != previousMouseEventData.pt.x)
{
int xChange = newMouseEventData.pt.x - previousMouseEventData.pt.x;
//Mouse movement left
if (xChange < 0)
{
cout << "Mouse left" << endl;
//A press down
//0 1 0 0 0000 01100001 0000000000000000
int keydownLparam = 0b01000000011000010000000000000000;
if (!PostMessage(newMouseEventData.hwnd, WM_KEYDOWN, 0x41, keydownLparam))
{
cout << GetLastError() << endl;
}
}
}
else
{
cout << "Mouse right" << endl;
}
}
}
catch(exception e){
cout << e.what() << endl;
}
}