DEV Community

Stacy Roll
Stacy Roll

Posted on

6

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

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

While many AI coding tools operate as simple command-response systems, Qodo Gen 1.0 represents the next generation: autonomous, multi-step problem-solving agents that work alongside you.

Read full post

Top comments (2)

Collapse
 
behainguyen profile image
Be Hai Nguyen

A sweet post Stacy, thank you.

Collapse
 
proteusiq profile image
Prayson Wilfred Daniel

Is there something like Python’s pynput where we can have callbacks?

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post