How to get the keys without pressing enter in rust ⌨️

stacy-roll

Stacy Roll

Posted on December 27, 2023

How to get the keys without pressing enter in rust ⌨️

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"] }
Enter fullscreen mode Exit fullscreen mode
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"),
            _ => (),
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

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!🥰

💖 💪 🙅 🚩
stacy-roll
Stacy Roll

Posted on December 27, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related