0

I'm trying to implement a simple program that records keystrokes, I followed a tutorial and ends up with this :

#define _CRT_SECURE_NO_DEPRECATE
#include <iostream>
#include <cstdio>
#include <Windows.h>

static HHOOK        hkb;
static FILE*        f1;

LRESULT CALLBACK    KeyboardProc(int nCode, WPARAM wParam, LPARAM lParam)
{
    char    c;
    std::cout << "inside hook" << std::endl;

    if (((DWORD)lParam & 0x40000000) && (HC_ACTION == nCode))
    {
        if ((wParam == VK_SPACE) || (wParam == VK_RETURN) || (wParam >= 0x2f) && (wParam <= 0x100))
        {
            f1 = fopen("report.txt", "a");
            std::cout << "inside if good" << std::endl;

            if (wParam == VK_RETURN)
            {
                c = '\n';
                fwrite(&c, 1, 1, f1);
            }
            else
            {
                BYTE    ks[256];
                GetKeyboardState(ks);

                WORD    w;
                UINT    scan = 0;
                ToAscii(wParam, scan, ks, &w, 0);
                c = (char)w;
                fwrite(&c, 1, 1, f1);
            }

            fclose(f1);
        }
    }

    LRESULT RetVal = CallNextHookEx(hkb, nCode, wParam, lParam);
    return  RetVal;
}

BOOL                installhook()
{
    f1 = fopen("report.txt", "w");
    fclose(f1);
    hkb = SetWindowsHookEx(WH_KEYBOARD, (HOOKPROC)KeyboardProc, NULL, GetCurrentThreadId());

    if (hkb == NULL)
    {
        std::cerr << "failed to set hook" << std::endl;
        return false;
    }

    return true;
}

int     main()
{
    installhook();

    std::cin.get();
    return 0;
}

The hook is apparently set correctly but it isn't called when I type something, hence none of my test std::cout in KeyboardProc() are reached.

Surely I missed something or failed to understand how hooks were working.

Kernael
  • 3,270
  • 4
  • 22
  • 42
  • Don't cast the callback when giving it to `SetWindowsHookEx`. If it doesn't compile, you're now masking the problem. – chris Nov 05 '14 at 13:49
  • @chris removed the cast, it still compiles but doesn't fix the problem. – Kernael Nov 05 '14 at 13:50

0 Answers0