From e180222ab9386cfdd9b081ccbc157a5e256790a7 Mon Sep 17 00:00:00 2001 From: hthuz Date: Wed, 11 Dec 2024 19:23:15 +0800 Subject: [PATCH] fix: event-read-char-line double read error & auto enter --- examples/event-read-char-line.rs | 41 +++++++++++++++++++++----------- 1 file changed, 27 insertions(+), 14 deletions(-) diff --git a/examples/event-read-char-line.rs b/examples/event-read-char-line.rs index 5fa834927..33c7f75cd 100644 --- a/examples/event-read-char-line.rs +++ b/examples/event-read-char-line.rs @@ -5,12 +5,13 @@ use std::io; -use crossterm::event::{self, Event, KeyCode, KeyEvent}; +use crossterm::{event::{self, Event, KeyCode, KeyEvent, KeyEventKind}, terminal}; pub fn read_char() -> io::Result { loop { if let Event::Key(KeyEvent { code: KeyCode::Char(c), + kind: KeyEventKind::Press, .. }) = event::read()? { @@ -21,24 +22,36 @@ pub fn read_char() -> io::Result { pub fn read_line() -> io::Result { let mut line = String::new(); - while let Event::Key(KeyEvent { code, .. }) = event::read()? { - match code { - KeyCode::Enter => { - break; - } - KeyCode::Char(c) => { - line.push(c); + loop { + if let Event::Key(KeyEvent{ + code, + kind: KeyEventKind::Press, + .. + }) = 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()); +fn main() -> io::Result<()> { + terminal::enable_raw_mode()?; + + println!("read line:\r"); + println!("{:?}\r", read_line()); + println!("read char:\r"); + println!("{:?}\r", read_char()); + println!("read char again:\r"); + println!("{:?}\r", read_char()); + + terminal::disable_raw_mode() }