| 1 |
//! Demonstrates the display format of key events. |
| 2 |
//! |
| 3 |
//! This example demonstrates the display format of key events, which is useful for displaying in |
| 4 |
//! the help section of a terminal application. |
| 5 |
//! |
| 6 |
//! cargo run --example key-display |
| 7 |
|
| 8 |
use std::io; |
| 9 |
|
| 10 |
use crossterm::event::KeyModifiers; |
| 11 |
use crossterm::{ |
| 12 |
event::{read, KeyCode}, |
| 13 |
terminal::{disable_raw_mode, enable_raw_mode}, |
| 14 |
}; |
| 15 |
|
| 16 |
const HELP: &str = r#"Key display |
| 17 |
- Press any key to see its display format |
| 18 |
- Use Esc to quit |
| 19 |
"#; |
| 20 |
|
| 21 |
fn main() -> io::Result<()> { |
| 22 |
println!("{}", HELP); |
| 23 |
enable_raw_mode()?; |
| 24 |
if let Err(e) = print_events() { |
| 25 |
println!("Error: {:?}\r", e); |
| 26 |
} |
| 27 |
disable_raw_mode()?; |
| 28 |
Ok(()) |
| 29 |
} |
| 30 |
|
| 31 |
fn print_events() -> io::Result<()> { |
| 32 |
while let Ok(event) = read() { |
| 33 |
let Some(event) = event.as_key_press_event() else { |
| 34 |
continue; |
| 35 |
}; |
| 36 |
let modifier = match event.modifiers { |
| 37 |
KeyModifiers::NONE => "".to_string(), |
| 38 |
_ => format!("{:}+", event.modifiers), |
| 39 |
}; |
| 40 |
println!("Key pressed: {modifier}{code}\r", code = event.code); |
| 41 |
if event.code == KeyCode::Esc { |
| 42 |
break; |
| 43 |
} |
| 44 |
} |
| 45 |
Ok(()) |
| 46 |
} |