c++ - 当条件产生时结束线程。 C/C++

标签 c++ c multithreading winapi

我有一个 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/

相关文章:

performance - 同时将变量更新为相同值的线程安全性

c++ - 在基类中转发声明嵌套结构

c - section 和 task openmp 的区别

c - 理解为 gcc 编写的 asm block

c - if 语句中只有变量名意味着什么

ios - 如何从 objective-c 方法异步分派(dispatch) C 函数

c# - C# Parallel.ForEach 的工作何时完成?

c++ - 是否可以在没有 Boost.Fusion 的情况下使用 Boost.Spirit V2.x?

c++ - 套接字身份验证和加密

c++全透明窗口但仍然阅读文本例如