jenslog-rs/src/key/keystate.rs
LordMZTE 8bba874cd6 move some stuff
key names will finally be correct
2020-08-26 14:24:52 +02:00

57 lines
1.9 KiB
Rust

use std::ffi::OsString;
use winapi::um::winuser::{GetKeyNameTextW, KBDLLHOOKSTRUCT};
use wio::wide::FromWide;
pub struct KeyState {
pub kbdllstruct: KBDLLHOOKSTRUCT,
pub shift_down: bool,
pub ctrl_down: bool,
pub win_down: bool,
}
impl KeyState {
pub fn new() -> Box<Self> {
Box::new(Self {
kbdllstruct: KBDLLHOOKSTRUCT {
vkCode: 0,
scanCode: 0,
flags: 0,
time: 0,
dwExtraInfo: 0,
},
shift_down: false,
ctrl_down: false,
win_down: false,
})
}
/// `key_down` if the event was a keydown event, this should be true. if it was keyup it should be false
pub fn update(&mut self, key: KBDLLHOOKSTRUCT, key_down: bool) {
self.kbdllstruct = key;
match key.vkCode {
160 | 161 => self.shift_down = key_down,
162 | 163 => self.ctrl_down = key_down,
91 => self.win_down = key_down,
_ => {}
}
}
/// true if the key is an auxiliary key like shift, control or the windows key
pub fn is_aux_key(&self) -> bool {
matches!(self.kbdllstruct.vkCode, 160 | 161 | 162 | 163 | 91)
}
#[no_mangle]
pub fn name(&self) -> String {
unsafe {
let mut out = [0_u16; 128];
GetKeyNameTextW((self.kbdllstruct.scanCode << 16 | 1 << 24 /*this distinguishes special keys by setting a flag. yes only microsoft thinks that input and flags in 1 param is a good idea*/) as i32, (&mut out).as_mut_ptr(), 128);
let null_pos = out.iter().position(|x| *x == b'\0' as u16).unwrap_or_else(|| out.len());
//use to_string_lossy to avoid unicode checks for better performance. if the windows api screws up thats not my fault :P
OsString::from_wide(&out[..null_pos]).to_str().unwrap().to_owned()
}
}
}