DEV Community

Stacy Roll
Stacy Roll

Posted on • Updated on

How to get the hex code of a key from my keyboard ? ๐Ÿ‘“

If you are studying your keyboard's behavior and want to know the hexadecimal value of the key event you wish to execute when pressing it, you can run this Rust code to obtain the exact value. If you don't have Rust installed, you can find the mapped values in the k_board library.

If you have rust installed, run the following command:

cargo new keys && cd keys && cargo add k_board

copy the code into the main.rs file, then

cargo run

use std::io::{Read, Write};

fn main() -> std::io::Result<()> {
    loop {
        let _ = get_key();
    }
}

pub fn get_key() -> std::io::Result<()> {
    let termios_enviroment: k_board::termios = k_board::setup_raw_mode().unwrap();
    std::io::stdout().flush().unwrap();
    let mut buffer: [u8; 3] = [0; 3];
    std::io::stdin().read(&mut buffer).unwrap();
    if buffer[0] != 0x00 {
        println!(
            "[0x{:x?}, 0x{:x?}, 0x{:x?}]",
            buffer[0], buffer[1], buffer[2]
        );
    }
    std::io::stdout().flush().unwrap();
    k_board::restore_termios(&termios_enviroment).unwrap();
    Ok(())
}
Enter fullscreen mode Exit fullscreen mode

Preview

video

Top comments (0)