我已经使用Rust中的termion箱创建了一个简单的命令行工具.它会打印出"Hello World!"按下键时的消息.只有当输入的是q
个字符时,它才会退出程序.以下是使用AlternateScreen
struct 在终端上编写的代码:
use std::io::{stdin, stdout, Write};
use termion::event::Key;
use termion::input::TermRead;
use termion::raw::IntoRawMode;
use termion::screen::IntoAlternateScreen;
fn main() {
// Initialize stdout and stind
let stdin = stdin();
let mut stdout = stdout().into_alternate_screen().unwrap();
// Print a message indicating what to do
write!(
stdout,
"{}{}Press any key to print 'Hello world!', or press 'q' to quit.{}",
termion::clear::All,
termion::cursor::Goto(1, 1),
termion::cursor::Hide
)
.unwrap();
stdout.flush().unwrap();
// Create an input reader for key events
let mut row = 1;
for c in stdin.keys() {
write!(
stdout,
"{}{}",
termion::cursor::Goto(1, row),
termion::clear::CurrentLine
)
.unwrap();
match c.unwrap() {
Key::Char('q') => break,
_ => println!("Hello world!"),
}
stdout.flush().unwrap();
row += 1;
}
// Enable back the cursor
write!(stdout, "{}", termion::cursor::Show).unwrap();
}
通过转到下一行和第一列,我将消息写到新行.row
变量跟踪下一条消息的写入位置.
问题是我必须按Enter来注册标准输入中的字符.然而,另一首《Hello World!》显示文本是因为额外的键.我想在任何输入键之后立即写入文本,而不需要按Enter按钮.
请注意,如果将标准输出替换为RawTerminal
struct ,则一切都将按预期运行.
let mut stdout = stdout().into_raw_mode().unwrap();
在这种情况下,不需要在输入字符上按Enter.
为什么AlternateScreen
在读取输入键时需要按Enter键?