【发布时间】:2014-09-26 13:46:08
【问题描述】:
我有一个 C 代码来检查鼠标左键是否被按下。它工作正常,但我想用它来计算按钮被点击的次数,并在按钮被随机点击次数时调用函数。
这是代码:
LRESULT CALLBACK mouseProc(int nCode, WPARAM wParam, LPARAM lParam)
{
int count = 0;
MOUSEHOOKSTRUCT * pMouseStruct = (MOUSEHOOKSTRUCT *)lParam;
if (pMouseStruct != NULL){
if (wParam == WM_LBUTTONDOWN)
{
count++;
printf("%d",count);
if (count==finalNum){ // user clicked random times the mouse so we launch the final function
printf("\ndone!\n");
final();
}
printf("clicked");
}
printf("Mouse position X = %d Mouse Position Y = %d\n", pMouseStruct->pt.x, pMouseStruct->pt.y);
}
return CallNextHookEx(hMouseHook, nCode, wParam, lParam);
}
DWORD WINAPI MyMouseLogger(LPVOID lpParm)
{
HINSTANCE hInstance = GetModuleHandle(NULL);
// here I put WH_MOUSE instead of WH_MOUSE_LL
hMouseHook = SetWindowsHookEx(WH_MOUSE_LL, mouseProc, hInstance, NULL);
MSG message;
while (GetMessage(&message, NULL, 0, 0)) {
TranslateMessage(&message);
DispatchMessage(&message);
}
UnhookWindowsHookEx(hMouseHook);
return 0;
}
void custom_delay(){
}
int main(int argc, char *argv[])
{
int count = 0;
HANDLE hThread;
DWORD dwThread;
//////Generate random number to call a function after rand() number of clicks
srand(time(NULL)); // Seed the time
int finalNum = rand() % (150 - 50) + 50; // Generate the number, assign to variable.
////////////////////////////////////////////////////////////////////////////
printf("%d", finalNum);
hThread = CreateThread(NULL, NULL, (LPTHREAD_START_ROUTINE)MyMouseLogger, (LPVOID)argv[0], NULL, &dwThread);
if (hThread)
return WaitForSingleObject(hThread, INFINITE);
else
return 1;
}
}
问题是每次发生鼠标事件时计数变量都会重置为 0,因此我无法跟踪用户用鼠标单击的次数。
另一个问题是我想生成 50 到 150 之间的随机次数来调用 final() 函数。如何发送该随机数作为参数?
感谢您的帮助!
【问题讨论】:
标签: c++ c winapi mouseevent hook