views:

205

answers:

2

hello, how would i read keystrokes using the win32 api? i would also like to see them from international keyboards like german umlauts.

thanks

+1  A: 

To get keyboard input regardless of focus, you'll probably need to hook the keyboard.

Take a look at SetWindowsHookEx with WH_KEYBOARD or WH_KEYBOARD_LL. Add a W to the call for the Unicode variant.

Jens Björnhager
+2  A: 

There's a difference between keyboard presses and the characters they generate.

At the lowest level, you can poll the keyboard state with GetKeyboardState. That's often how keylogging malware does it, since it requires the least privileges and sees everything regardless of where the focus is. The problem with this approach (besides requiring constant polling) is that you have to piece together the keyboard state into keystrokes and then keystrokes into a character stream. You have to know how the keyboard is mapped, you have keep state of shift keys, control keys, alt keys, etc. You have to know about auto-repeat, dead keys, and possibly other complications.

If you have privileges you can install a keyboard hook, as Jens mentioned in his answer.

If you have focus, and you're a console app, you use one of the functions to read from standard input. On Windows, it's hard to get true Unicode input. You generally get so-called ANSI characters, which correspond to the current code page for the console window. If you know the code page, you can use MultiByteToWideChar to convert the single- or multi-byte input into UTF-16 (which Windows documentation calls Unicode). From there you can convert it to UTF-8 (with WideCharToMultiByte) or whatever other Unicode encoding you want.

If you have focus, and you're a GUI app, you can see keystrokes with WM_KEYDOWN (and friends). You can can also get fully resolved UTF-16 characters with WM_CHAR (or UTF-32 from WM_UNICHAR). If you need UTF-8 from those, you'll have to do a conversion.

Adrian McCarthy