Capturing keystrokes

Chris wendlec at tcd.ie
Fri Feb 7 08:58:47 PST 2014


On Friday, 7 February 2014 at 16:21:20 UTC, Chris wrote:
> On Friday, 7 February 2014 at 15:40:06 UTC, Adam D. Ruppe wrote:
>> 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.
>
> I just had a look at terminal.d. Great stuff. It works, though 
> it sometimes stops working and gives me this exception (after 
> killing it with Ctrl+C):
>
> object.Exception at terminal.d(814): write failed for some reason
>
> There is a syntax error on line 54;
>
> version = Demo
>
> should be
>
> version = Demo;
>
> I'll have a look at your other stuff too, it looks very 
> interesting.

It actually breaks when I press a modifier key like Ctrl.


More information about the Digitalmars-d mailing list