Skip to content

Instantly share code, notes, and snippets.

@sbarratt
Created May 31, 2016 19:49
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save sbarratt/3077d5f51288b39665350dc2b9e19694 to your computer and use it in GitHub Desktop.
Save sbarratt/3077d5f51288b39665350dc2b9e19694 to your computer and use it in GitHub Desktop.
Create a keyboard hook using Win32 System API and log what the user types into a console.
#include <stdio.h>
#include <tchar.h>
#include <Windows.h>
#include <iostream>
HHOOK hHook{ NULL };
enum Keys
{
ShiftKey = 16,
Capital = 20,
};
int shift_active() {
return GetKeyState(VK_LSHIFT) < 0 || GetKeyState(VK_RSHIFT) < 0;
}
int capital_active() {
return (GetKeyState(VK_CAPITAL) & 1) == 1;
}
LRESULT CALLBACK keyboard_hook(const int code, const WPARAM wParam, const LPARAM lParam) {
if (wParam == WM_KEYDOWN) {
KBDLLHOOKSTRUCT *kbdStruct = (KBDLLHOOKSTRUCT*)lParam;
DWORD wVirtKey = kbdStruct->vkCode;
DWORD wScanCode = kbdStruct->scanCode;
BYTE lpKeyState[256];
GetKeyboardState(lpKeyState);
lpKeyState[Keys::ShiftKey] = 0;
lpKeyState[Keys::Capital] = 0;
if (shift_active()) {
lpKeyState[Keys::ShiftKey] = 0x80;
}
if (capital_active()) {
lpKeyState[Keys::Capital] = 0x01;
}
char result;
ToAscii(wVirtKey, wScanCode, lpKeyState, (LPWORD)&result, 0);
std::cout << result << std::endl;
}
return CallNextHookEx(hHook, code, wParam, lParam);
}
int main(int argc, char* argv[])
{
hHook = SetWindowsHookEx(WH_KEYBOARD_LL, keyboard_hook, NULL, 0);
if (hHook == NULL) {
std::cout << "Keyboard hook failed!" << std::endl;
}
while (GetMessage(NULL, NULL, 0, 0));
return 0;
}
@Valtsuh
Copy link

Valtsuh commented Jan 19, 2022

Thank you, very helpful.

@Shtille
Copy link

Shtille commented Apr 3, 2023

This won't work on Windows later than XP (Vista, 7, 8, 10) since it will require HINSTANCE parameter hmod to be non null (in function SetWindowsHookEx). It should contain DLL HINSTANCE.

@DoctorCocoBean
Copy link

Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment