iohook
iohook copied to clipboard
How to get the actual character typed?
I used String.fromCharCode(key.rawcode) to obtain Q Q and 1 1 even though I really typed q Q and + 1. In other words, I get the same character code for lower and capital form of a letter. Notice how keypress library handles that.
While your solution is far superior with regard to giving same output with different layouts, it is useful to also get the actual character typed.
I pressed
q = q
shiftq = Q

I pressed
+ = +
shift+ = 1 (Czech Qwerty layout )

@ackvf Instead of String.fromCharCode(key.rawcode) do String.fromCharCode(key.keychar).
@Richienb keychar is not defined on the object though.
@ackvf It works for me. Check the version you have installed.
I have just updated from 0.6.4 to 0.6.5 and the keychar is still undefined.
@ackvf Try this code:
const iohook = require("iohook")
iohook.start()
iohook.on("keypress", ({ keychar }) => console.log(`Key pressed: ${String.fromCharCode(keychar)}`))
So, the problem is that I am using keydown instead of keypress, anyway, observe:

- focused main window,
keypresswon't fire at all. - focused another terminal,
keypresswon't fire at all. - focused notepad,
keypressstarts firing.
The difference between those two for the key a:

import iohook from 'iohook'
iohook.start()
iohook.on("keypress", key => console.log(`keypress: ${JSON.stringify(key)}`) )
iohook.on("keydown", key => console.log(`keydown: ${JSON.stringify(key)}`) )
Is this a bug?
I have the same behaviour of you, and I think it's a bug because a few week ago, I didn't think I had this problem
I'm able to get the unicode keychar in the keydown event similar to the keypress event by modifying a couple of source files and rebuilding
Lower case "a"
{"shiftKey":false,"altKey":false,"ctrlKey":false,"metaKey":false,"keychar":97,"keycode":30,"rawcode":0,"type":"keydown"}
Upper case "A" with shift key
{"shiftKey":true,"altKey":false,"ctrlKey":false,"metaKey":false,"keychar":65,"keycode":30,"rawcode":0,"type":"keydown"}
Replace line 364 in input_hook.c with:
UniChar keycharBuffer; keycode_to_unicode(event_ref, &keycharBuffer, KEY_BUFFER_SIZE); event.data.keyboard.keychar = keycharBuffer;
Change line 447 in iohook.cc:
From: if (event.type == EVENT_KEY_TYPED) {
To: if (event.type == EVENT_KEY_TYPED || event.type == EVENT_KEY_PRESSED) {
I tested only on a Mac, but similar changes should apply for Windows by replacing line 226 in input_hook.c file for Windows with:
WCHAR keycharBuffer[2]; keycode_to_unicode(kbhook->vkCode, &keycharBuffer, sizeof(buffer)) event.data.keyboard.keychar = keycharBuffer;