全局挂钩在 Visual C++ 中不起作用

Global Hooks not working in Visual C++

我编写这个基本的 C++ 应用程序是为了理解 Windows 全局挂钩,因为我是新手。不幸的是,这在 Qt Creator 上运行完美,但在 Visual Studio 上运行得不是很好。事实上,它在 VS2013 中什么都不做。谁能详细说说为什么?这真的很有帮助!

#include <iostream>
#include <fstream>
#include <Windows.h>
#pragma comment(lib, "user32.lib")

HHOOK hHook{ NULL };

LRESULT CALLBACK MyLowLevelKeyBoardProc(const int nCode, const WPARAM wParam, const LPARAM lParam)
{
    std::cout << "Key Pressed!";
    return CallNextHookEx(hHook, nCode, wParam, lParam);
}

int main(int argc, char* argv[])
{
    hHook = SetWindowsHookEx(WH_KEYBOARD_LL, MyLowLevelKeyBoardProc, NULL, 0);
    if (hHook == NULL) {
        std::cout << "Hook failed!" << std::endl;
    }

    return 0;
}

我已遵循教程 given here。我也尝试过查阅许多在线文档,但我无法修复它,可能是因为我通常使用 C# 而不是 C++。

更新:这是 Qt 应用程序的样子。几乎一样,只是主函数有点不同,std::cout 被 QDebug() 代替了。还有一些额外的#include.

#include<QtCore/QCoreApplicaton>
#include<QDebug>
#include<QTime>
#include<QChar>

int main(int argc, char* argv[])
{
    QCoreApplication a(argc, argv);

    hHook = SetWindowsHookEx(WH_KEYBOARD_LL, MyLowLevelKeyBoardProc, NULL, 0);
    if (hHook == NULL) {
        QDebug() << "Hook failed!";
    }

    return a.exec();
}

第一个应用程序将设置挂钩,但随后会立即终止程序。

带有 return a.exec() 的 Qt 应用程序运行一个消息循环,该循环只会在您关闭程序时终止。这就是它保持开放的原因。

编辑:

你必须 "pump the windows message loop",试试下面的代码 (from wikipedia)

MSG msg;
BOOL bRet;

while((bRet = GetMessage(&msg, NULL, 0, 0)) != 0)
{
    if(bRet == -1)
    {
        // Handle Error
    }
    else
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
}

如果您收到 WM_QUIT 消息,您可以终止程序。

另一种更简单、更容易的方法是将以下代码行放在 return 语句之前。

while (GetMessage(NULL, NULL, 0, 0));