我有一个 C 代码,用于检查鼠标左键是否已被按下。它工作正常,但我不知道如何在调用 Final() 函数后取消 Hook 并退出当前线程。
这是代码:
LRESULT CALLBACK mouseProc(int nCode, WPARAM wParam, LPARAM lParam)
{
static int count = 0;
static int finalNum;
if (count==0){
//////Generate random number
srand(time(NULL)); // Seed the time
finalNum = rand() % (150 - 50) + 50; // Generate the number, assign to variable.
////////////////////////////////////////////////////////////////////////////
}
//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;
}
printf("Keep going");
}
我尝试过 ExitThread(0);但它会关闭所有线程,而不仅仅是 MyMouseLogger 进程来打印“继续”。
我该怎么做?
感谢您的帮助!
最佳答案
您可以使用PostThreadMessage向线程发送WM_QUIT,这将导致其消息循环退出。
关于c++ - 当条件产生时结束线程。 C/C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25114182/