The standard rust library does not support getting keyboard events in raw mode to capture keys without pressing enter. So, if you are in linux: in this post I am going to show you how to obtain the events and keys using the lightweight crate k_board.
[dependencies]
k_board = { version = "1.2.1", features = ["standar", "f", "alt_lower_letter", "ctrl_lower_letter", "lower_letter"] }
use k_board::{keyboard::Keyboard, keys::Keys};
fn main() {
for key in Keyboard::new() {
match key {
Keys::Char('q') => break,
Keys::Up => println!("Up arrow press"),
Keys::Ctrl('t') => println!("Ctrl + t press"),
Keys::Alt('p') => println!("Alt + p press"),
Keys::Char('+') => println!("+ press"),
Keys::F(2) => println!("F2 press"),
Keys::Char('7') => println!("7 press"),
_ => (),
}
}
}
What do features do?
Considering that efficiency in code is vital for developing a high-performance program, you can choose which parts of the keyboard will be listened to during runtime. If you only want to use the arrow keys and enter for your program, you can simply add it to your repository without features. However, if you want to use letters, numbers, special combinations, then you'll have to add it as a feature.
See you in the next post!🥰
Top comments (2)
A sweet post Stacy, thank you.
Is there something like Python’s pynput where we can have callbacks?