How i can detect arrow keys with arsd.terminal?
Adam D. Ruppe
destructionator at gmail.com
Fri Apr 11 19:59:43 UTC 2025
On Friday, 11 April 2025 at 13:51:59 UTC, Zoda wrote:
> i want to detect arrow keys with
> arsd.terminal.RealTimeConsoleInput,
> how can i do that?
The secret is kinda tucked away but here's the enum that defines
these keys as magic characters:
https://opendlang.org/library/arsd.terminal.KeyboardEvent.Key.html
You can use that in a switch along with other characters in a
getch loop:
```
import arsd.terminal;
void main() {
auto terminal = Terminal(ConsoleOutputType.linear);
auto rtti = RealTimeConsoleInput(&terminal,
ConsoleInputFlags.raw);
loop: while(true) {
switch(rtti.getch()) {
case 'q': // other characters work as
chars in the switch
break loop;
case KeyboardEvent.Key.F1: // also f-keys
via that enum
terminal.writeln("You pressed
F1!");
break;
case KeyboardEvent.Key.LeftArrow: //
arrow keys, etc.
terminal.writeln("left");
break;
case KeyboardEvent.Key.RightArrow:
terminal.writeln("right");
break;
default: {}
}
}
}
```
See other notes at the top of this page:
https://opendlang.org/library/arsd.terminal.KeyboardEvent.html
If you also need to check for things like shift+arrows, that may
be possible (depends on your terminal) but will require you write
a full event loop with the `nextEvent` function and it is quite a
bit more involved.
https://opendlang.org/library/arsd.terminal.RealTimeConsoleInput.nextEvent.html
Note that if you want to just get a line of text from an editor,
that's what Terminal.getline is for, has some features similar to
gnu readline. It can be extensively customized as well to add tab
complete, syntax highlighting, and more by subclassing
LineGetter. You can also run your own event loop and filter the
events you forward to the linegetter and custom responding to
others for maximum control, but that gets quite involved.
More information about the Digitalmars-d
mailing list