Some quick and dirty code to reimplement window

switch detection and process name lookup
This commit is contained in:
Your Name
2022-06-12 11:19:46 -04:00
commit a61e3e5d3a
5 changed files with 194 additions and 0 deletions

58
src/main.rs Normal file
View File

@@ -0,0 +1,58 @@
mod pid_to_exe;
use std::ptr::null_mut;
use winapi::{
shared::windef::{HWINEVENTHOOK__, HWND__},
um::winuser::{
DispatchMessageW, GetMessageW, GetWindowThreadProcessId, TranslateMessage,
EVENT_SYSTEM_FOREGROUND, EVENT_SYSTEM_MINIMIZEEND, MSG, WINEVENT_OUTOFCONTEXT,
WINEVENT_SKIPOWNPROCESS,
},
};
use crate::pid_to_exe::pid_to_exe_path;
unsafe extern "system" fn win_event_proc(
_hook: *mut HWINEVENTHOOK__,
event: u32,
hwnd: *mut HWND__,
_id_object: i32,
_id_child: i32,
_dw_event_thread: u32,
_dwms_event_time: u32,
) {
if event == EVENT_SYSTEM_FOREGROUND || event == EVENT_SYSTEM_MINIMIZEEND {
let mut pid: u32 = 0;
GetWindowThreadProcessId(hwnd, &mut pid);
println!("{:?}", pid_to_exe_path(pid));
}
}
fn main() {
unsafe {
winapi::um::winuser::SetWinEventHook(
EVENT_SYSTEM_FOREGROUND,
EVENT_SYSTEM_FOREGROUND,
null_mut(),
Some(win_event_proc),
0,
0,
WINEVENT_OUTOFCONTEXT | WINEVENT_SKIPOWNPROCESS,
);
winapi::um::winuser::SetWinEventHook(
EVENT_SYSTEM_MINIMIZEEND,
EVENT_SYSTEM_MINIMIZEEND,
null_mut(),
Some(win_event_proc),
0,
0,
WINEVENT_OUTOFCONTEXT | WINEVENT_SKIPOWNPROCESS,
);
let mut msg: MSG = Default::default();
while GetMessageW(&mut msg, null_mut(), 0, 0) > 0 {
TranslateMessage(&msg);
DispatchMessageW(&msg);
}
}
}

26
src/pid_to_exe.rs Normal file
View File

@@ -0,0 +1,26 @@
use std::ptr::null_mut;
use winapi::{
shared::minwindef::{DWORD, FALSE, MAX_PATH},
um::{
errhandlingapi::GetLastError,
processthreadsapi::OpenProcess,
winbase::QueryFullProcessImageNameW,
winnt::{PROCESS_QUERY_INFORMATION, PROCESS_VM_READ},
},
};
pub unsafe fn pid_to_exe_path(pid: u32) -> Result<String, DWORD> {
let mut exe_name = Vec::with_capacity(MAX_PATH);
let mut size: u32 = exe_name.capacity().try_into().unwrap();
let process = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pid);
if process == null_mut() {
return Err(GetLastError());
}
if QueryFullProcessImageNameW(process, 0, exe_name.as_mut_ptr(), &mut size) == FALSE {
return Err(GetLastError());
}
exe_name.set_len(size.try_into().unwrap());
let process_name = String::from_utf16_lossy(&exe_name);
return Ok(process_name);
}