10

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.

Shepmaster
  • 326,504
  • 69
  • 892
  • 1,159
ca1ek
  • 347
  • 3
  • 12

1 Answers1

5

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");
}
Shepmaster
  • 326,504
  • 69
  • 892
  • 1,159
Constantin
  • 8,351
  • 12
  • 74
  • 119
  • it seems that method `get_keys()` is non-blocking , it will return immediately , so the main program keep polling ? – Chris.Huang Dec 01 '21 at 12:46