A safe wrapper around the Windows Hook API for Rust.
This crate provides a safe interface to the Windows Hook API, enabling you to set and unset hooks for various events, including keyboard and mouse input. The WindowsHook struct wraps the underlying winsafe::HHOOK type and automatically unsets itself when it goes out of scope.
A builder pattern is also provided, as well as wrappers for the Keyboard_LL (KeyboardLLHook) and Mouse_LL (MouseLLHook) hooks.
These wrappers automate ownership and the drop of these hooks.
use windows_hook::{WindowsHook, WH, Handle, HHOOK, Module, ThreadId};
extern "system" fn your_hook_fn(code: i32, wparam: usize, lparam: isize) -> isize {
/// simple passthrough
HHOOK::NULL.CallNextHookEx(unsafe { WH::from_raw(code) }, wparam, lparam)
}
let mut hook = WindowsHook::set_new(WH::KEYBOARD_LL, your_hook_fn, Module::NULL, ThreadId::NONE).unwrap();
assert!(hook.state().is_set());
// hook will unset when it drops out of scope, but it can also be unset manually.
hook.unset().unwrap();Builder pattern:
use windows_hook::{WindowsHookBuilder, WH, Handle, HHOOK, Module, ThreadId};
extern "system" fn your_hook_fn(code: i32, wparam: usize, lparam: isize) -> isize {
/// simple passthrough
HHOOK::NULL.CallNextHookEx(unsafe { WH::from_raw(code) }, wparam, lparam)
}
let hook = WindowsHookBuilder::new(WH::KEYBOARD_LL, your_hook_fn)
.with_module(Module::NULL)
.with_thread_id(ThreadId::NONE)
.build_and_set().unwrap();
assert!(hook.state().is_set());tracing: Enable tracing support - reports errors when the hook is dropped
Module: A module handle, similar to (and convertible to) thewinsafe::HMODULE/HINSTANCEtype.ThreadId: A thread id wrapper.
- Add additional support for hooks where it would be convenient to bundle the loaded library, and drop it with the hook.