'How to listen to all keypresses in Winapi and cancel some of them?

I'm trying to write an keyboard software debounce program in C(++) for my crappy keyboard that double-clicks.

I apparently need to set a hook to WM_KEYBOARD_LL, but I a) couldn't do it, I have "invalid handle" errors and b) don't know how to cancel the keypresses, as I also want to do this for gaming.

How would I properly implement this?

Thanks in advance!

EDIT: Here is the non-working code I found somewhere

#include "windows.h"
#include <iostream>
using namespace std;

HHOOK hookHandle;

LRESULT CALLBACK keyHandler(int nCode, WPARAM wParam, LPARAM lParam);

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

  hookHandle = SetWindowsHookEx(WH_KEYBOARD_LL, keyHandler, NULL, 0);

  if (hookHandle == NULL)
  {
    cout << "ERROR CREATING HOOK: ";
    cout << GetLastError() << endl;
    getchar();
    return 0;
  }

  MSG message;

  while (GetMessage(&message, NULL, 0, 0) != 0)
  {
    TranslateMessage(&message);
    DispatchMessage(&message);
  }

  cout << "Press any key to quit...";
  getchar();

  UnhookWindowsHookEx(hookHandle);

  return 0;
}

LRESULT CALLBACK keyHandler(int nCode, WPARAM wParam, LPARAM lParam)
{
  cout << "Hello!" << endl;

  // Checks whether params contain action about keystroke
  if (nCode == HC_ACTION)
  {
    cout << ((KBDLLHOOKSTRUCT *)lParam)->vkCode << endl;
  }

  return CallNextHookEx(hookHandle, nCode,
                        wParam, lParam);
}

I am compiling it with Mingw-W64 on Linux, but error reproduces on MSVC and Mingw-W64 on Windows.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source