RegisterWaitForInputIdle中的回调函数没有按预期执行

问题描述 投票:0回答:0

我正在尝试使用 RegisterWaitForInputIdle 执行回调函数,但似乎代码有问题,它不会让回调执行并继续,我已经尝试逐步调试但遗憾的是它没有执行。

这是代码:

#include <iostream>
#include <Windows.h>

#pragma comment (lib, "kernel32.lib")

VOID CALLBACK CallbackFunc(PVOID lpParameter, BOOLEAN TimerOrWaitFired)
{
    std::cout << "Callback function called." << std::endl;
}

int main()
{
    // Load kernel32.dll
    HMODULE hModule = LoadLibraryA("kernel32.dll");
    if (!hModule) {
        std::cerr << "Failed to load kernel32.dll." << std::endl;
        return 1;
    }

    // Get the RegisterWaitForInputIdle function
    auto RegisterWaitForInputIdleFunc = reinterpret_cast<BOOL(WINAPI*)(HANDLE, DWORD, WAITORTIMERCALLBACK, PVOID, ULONG, DWORD)>(GetProcAddress(hModule, "RegisterWaitForInputIdle"));
    if (!RegisterWaitForInputIdleFunc) {
        std::cerr << "Failed to get RegisterWaitForInputIdle function." << std::endl;
        return 1;
    }

    // Create a waitable timer
    HANDLE hTimer = CreateWaitableTimer(NULL, FALSE, NULL);
    if (!hTimer) {
        std::cerr << "Failed to create waitable timer." << std::endl;
        return 1;
    }

    // Set the timer to trigger after 5 seconds
    LARGE_INTEGER liDueTime;
    liDueTime.QuadPart = -200000000LL; // 5 seconds
    if (!SetWaitableTimer(hTimer, &liDueTime, 0, NULL, NULL, FALSE)) {
        std::cerr << "Failed to set waitable timer." << std::endl;
        CloseHandle(hTimer);
        return 1;
    }

    // Register the wait with RegisterWaitForInputIdle
    DWORD dwThreadId = GetCurrentThreadId();
    if (!RegisterWaitForInputIdleFunc(hTimer, dwThreadId, (WAITORTIMERCALLBACK)CallbackFunc, NULL, INFINITE, WT_EXECUTEDEFAULT)) {
        std::cerr << "Failed to register wait." << std::endl;
        CloseHandle(hTimer);
        return 1;
    }

    std::cout << "Wait registered." << std::endl;

    // Wait for the timer to trigger
    DWORD dwRet = WaitForSingleObject(hTimer, INFINITE);
    if (dwRet == WAIT_OBJECT_0) {
        std::cout << "Timer triggered." << std::endl;
    }
    else {
        std::cerr << "Wait failed with error: " << GetLastError() << std::endl;
    }

    CloseHandle(hTimer);
    system("PAUSE");
    return 0;
}

期待解决方案和建议。

c++ winapi
© www.soinside.com 2019 - 2024. All rights reserved.