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.
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");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With