2024-01-11 02:04:43 +00:00
|
|
|
//! Demonstrates how to block read characters or a full line.
|
|
|
|
//! Just note that crossterm is not required to do this and can be done with `io::stdin()`.
|
|
|
|
//!
|
|
|
|
//! cargo run --example event-read-char-line
|
|
|
|
|
|
|
|
use std::io;
|
|
|
|
|
2024-01-11 02:21:34 +00:00
|
|
|
use keyfork_crossterm::event::{self, Event, KeyCode, KeyEvent};
|
2024-01-11 02:04:43 +00:00
|
|
|
|
2024-01-16 02:44:48 +00:00
|
|
|
/// Read a character from input.
|
2024-01-11 02:04:43 +00:00
|
|
|
pub fn read_char() -> io::Result<char> {
|
|
|
|
loop {
|
|
|
|
if let Event::Key(KeyEvent {
|
|
|
|
code: KeyCode::Char(c),
|
|
|
|
..
|
|
|
|
}) = event::read()?
|
|
|
|
{
|
|
|
|
return Ok(c);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-01-16 02:44:48 +00:00
|
|
|
/// Read a line from input.
|
2024-01-11 02:04:43 +00:00
|
|
|
pub fn read_line() -> io::Result<String> {
|
|
|
|
let mut line = String::new();
|
|
|
|
while let Event::Key(KeyEvent { code, .. }) = event::read()? {
|
|
|
|
match code {
|
|
|
|
KeyCode::Enter => {
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
KeyCode::Char(c) => {
|
|
|
|
line.push(c);
|
|
|
|
}
|
|
|
|
_ => {}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
Ok(line)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn main() {
|
|
|
|
println!("read line:");
|
|
|
|
println!("{:?}", read_line());
|
|
|
|
println!("read char:");
|
|
|
|
println!("{:?}", read_char());
|
|
|
|
}
|