ncurses를 사용하는 @ Jon의 솔루션이 작동하는 동안 ncurses는 의도적으로 화면을 지 웁니다. 내 작은 프로젝트에 대해 Rust를 배우기 위해 termios crate을 사용하는이 솔루션을 생각해 냈습니다. 이 아이디어는 ECHO
과 ICANON
플래그를 termios 바인딩을 통해 tcsetattr
에 액세스하여 수정하는 것입니다. (이들의 ncurses를 캡처 할 수 있지만) 단일 바이트를 판독
extern crate termios;
use std::io;
use std::io::Read;
use std::io::Write;
use termios::{Termios, TCSANOW, ECHO, ICANON, tcsetattr};
fn main() {
let stdin = 0; // couldn't get std::os::unix::io::FromRawFd to work
// on /dev/stdin or /dev/tty
let termios = Termios::from_fd(stdin).unwrap();
let mut new_termios = termios.clone(); // make a mutable copy of termios
// that we will modify
new_termios.c_lflag &= !(ICANON | ECHO); // no echo and canonical mode
tcsetattr(stdin, TCSANOW, &mut new_termios).unwrap();
let stdout = io::stdout();
let mut reader = io::stdin();
let mut buffer = [0;1]; // read exactly one byte
print!("Hit a key! ");
stdout.lock().flush().unwrap();
reader.read_exact(&mut buffer).unwrap();
println!("You have hit: {:?}", buffer);
tcsetattr(stdin, TCSANOW, & termios).unwrap(); // reset the stdin to
// original termios data
}
한가지 장점은 화살표 키를 캡처, CTRL-F 등의 확장 키를 포착하지 않는다.
이 솔루션은 UNIX와 같은 플랫폼을 대상으로합니다. 나는 Windows에 대한 경험이 없지만이 forum에 따르면 아마도 Windows에서는 SetConsoleMode
을 사용하여 비슷한 결과를 얻을 수 있습니다.
이것은 언어 문제가 아닌 플랫폼 문제입니다. 창문에는 문자 입력 기능이 있지만 유닉스/리눅스에서는 터미널을 라인 버퍼 모드에서 꺼내야합니다. –
언급 된 SO 링크에서'getch' 함수를 사용할 수 있습니다. 이를 공유 객체로 컴파일하고 Rust에서 사용해야합니다. https://gist.github.com/ihrwein/a4558d63d9250ee0bbf6 C 컴파일러가 필요하며 Linux에서만 작동합니다 (적어도 테스트 해봤습니다). . –