Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get keyboard input without the user pressing the Enter key?

Tags:

rust

I would use ncurses but I want it to run on Windows. In C++, I could use kbhit() and getch() from conio to first check if a character was pressed, then get it.

I would like something similar in Rust.

like image 778
ca1ek Avatar asked Feb 27 '16 16:02

ca1ek


1 Answers

With the crate device_query you can query the keyboard state without requiring an active window. You just need to add in your Cargo.toml file the dependency to this crate:

[dependencies]
device_query = "0.1.0"

The usage is straightforward and similar to kbhit() and getch(). The difference is you'll receive a Vec of pressed keys (Keycode) and this Vec will be empty if no key is pressed. A single call covers the functionality of both kbhit() and getch() combined.

use device_query::{DeviceQuery, DeviceState, Keycode};

fn main() {
    let device_state = DeviceState::new();
    loop {
        let keys: Vec<Keycode> = device_state.get_keys();
        for key in keys.iter() {
            println!("Pressed key: {:?}", key);
        }
    }
}

This program will print out all pressed keys on the console. To instead just check if any key is pressed (like with kbhit() only), you could use is_empty() on the returned Vec<> like this:

let keys: Vec<Keycode> = device_state.get_keys();
if !keys.is_empty(){
    println!("kbhit");
}
like image 54
Constantin Avatar answered Oct 16 '22 22:10

Constantin