I am creating a keystroke logger for my personal interest, as well wanting to know how to capture and use them as functions (like key shortcuts).
I got the code to l
Basically, you want to use this function:
HHOOK SetWindowsHookEx(
__in int idHook,
__in HOOKPROC lpfn,
__in HINSTANCE hMod,
__in DWORD dwThreadId
);
You can read up on what the parameters mean (and there's plenty of examples around) but the part that answers your question is the second parameter. You set lpfn
to point to a callback function, and every time a key is pressed your function (the one that logs the keystroke) gets called.
It's not just for the keyboard events either, check it out: SetWindowsHook()
On Windows, you need to insert a low level keyboard hook with the windows API. Then you will get a callback on your LowLevelKeyboardProc function, which you can then use to log. This will use pretty much 0% CPU and is guaranteed to catch every key.
As for handling a global key press to quit the logger, you could look for it in LowLevelKeyboardProc since you will be intercepting every key, but a better solution is to use RegisterHotKey and then look for WM_HOTKEY events in the message loop. It is a better solution because
Your program essentially eats up whatever CPU time it can because it never has a reason to stop executing - when it hits the end of the loop it immediately begins again, and there's no reason to delay in any of its processing within the loop body.
Most applications don't continuously poll the state of the keyboard, but instead listen for keyboard events broadcast by the OS. While listening for an event, your program has no need to consume CPU time and thus will sleep until an event occurs, freeing the processor for usage until then.
(Games are often an exception to this, in that they'll often poll the keyboard state. However, they typically limit how often they do this - usually to once a frame at most - and thus the CPU usage is still bounded.)