Crossterm is a Rust crate for detecting and reacting to terminal input as it happens. It can observe keyboard input, mouse input, and screen resizing while supporting both Unix/Linux and Windows terminals. section 23.2.1
Crossterm represents terminal interaction through events:
- read() waits until an event occurs, making it useful when the program only needs to react to input. section 23.2.1
- poll() checks for an event for a chosen Duration, including zero duration, so an application can update continuously without waiting for a key. section 23.4.2
- Keyboard events expose the character, modifier keys such as Shift, and whether the key was pressed or released. section 23.2.1
A minimal event loop
Add crossterm = "0.26.1" to Cargo.toml, import crossterm::event::read, and call read().unwrap() inside a loop. Printing each result reveals the events generated as keys are pressed and released. A stopwatch can instead use poll(Duration::from_millis(0)) so it redraws while still checking for input. section 23.2.1 section 23.4.2
use crossterm::event::read;
fn main() {
loop {
println!("{:?}", read().unwrap());
}
}
Runnable minimal loop for inspecting Crossterm keyboard events. section 23.2.1
