Capturing keystrokes

Adam D. Ruppe destructionator at gmail.com
Fri Feb 7 07:40:04 PST 2014


On Friday, 7 February 2014 at 12:17:42 UTC, Chris wrote:
> Just out of interest, is there a way of capturing keystrokes in 
> D?

This isn't so much a D question as a C one - the operating 
system's C api will give a way, then you use those same functions 
in D.

If you want input from your own terminal, my terminal.d might 
help. See the demo main here:

https://github.com/adamdruppe/misc-stuff-including-D-programming-language-web-stuff/blob/master/terminal.d#L2007


It captures as much info as possible in real time, optionally 
including window resize events, mouse motion and clicks, and key 
presses. (Also key releases on Windows, but such information is 
/not/ available on Linux.)

Ctrl+x keys are sent as as low ascii values. Ctrl+a is cast(char) 
1. Ctrl+b is cast(char) 2. Ctrl+c is sent as cast(char) 3 (though 
note control+c is captured by the OS and sent as an interrupt 
signal instead - my lib can catch that too). and so on through 
Ctrl+z which is 26.


You can get more information by doing a GUI program but then 
you'll have to do text output as gui too, so not as easy as cli. 
Of course, you could write a terminal emulator and have the best 
of both worlds... i've done it :)

https://github.com/adamdruppe/terminal-emulator


But I think terminal.d is what you want.



Now, if you want to capture input from ANY window, not just your 
own, on Windows you can use the API to capture the keyboard, on X 
you can listen to events on the root window, and on Linux you can 
also read /dev/input to get raw keyboard events (if you like, I 
have a small lib that can help with this too). Note that reading 
/dev/input needs your program to be root.


More information about the Digitalmars-d mailing list