Created
May 31, 2016 19:49
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} |
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.
Thank you!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you, very helpful.