From 0be299e8ee100828ee82dba40e06627ee32e16df Mon Sep 17 00:00:00 2001 From: Zachary Canann Date: Tue, 31 Dec 2024 00:40:33 -0800 Subject: [PATCH] Use more accurate DwmGetWindowAttribute for getting window bounds on Windows --- Cargo.toml | 1 + src/targets/win/mod.rs | 21 ++++++++++++++++++--- 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 29c7f56..830499f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -22,6 +22,7 @@ sysinfo = "0.30.0" windows-capture = "1.3.6" windows = { version = "0.58", features = [ "Win32_Foundation", + "Win32_Graphics_Dwm", "Win32_Graphics_Gdi", "Win32_UI_HiDpi", "Win32_UI_WindowsAndMessaging", diff --git a/src/targets/win/mod.rs b/src/targets/win/mod.rs index 9c78292..42914f9 100644 --- a/src/targets/win/mod.rs +++ b/src/targets/win/mod.rs @@ -1,5 +1,7 @@ use super::{Display, Target}; +use windows::Win32::Graphics::Dwm::{DwmGetWindowAttribute, DWMWA_EXTENDED_FRAME_BOUNDS}; use windows::Win32::UI::HiDpi::{GetDpiForMonitor, GetDpiForWindow, MDT_EFFECTIVE_DPI}; +use windows::Win32::UI::WindowsAndMessaging::GetWindowRect; use windows::Win32::{ Foundation::{HWND, RECT}, Graphics::Gdi::HMONITOR, @@ -87,7 +89,20 @@ pub fn get_target_dimensions(target: &Target) -> (u64, u64) { // get width and height of the window let mut rect = RECT::default(); - let _ = windows::Win32::UI::WindowsAndMessaging::GetWindowRect(hwnd, &mut rect); + + // Try DwmGetWindowAttribute first for accurate bounds without shadows + let result = DwmGetWindowAttribute( + hwnd, + DWMWA_EXTENDED_FRAME_BOUNDS, + &mut rect as *mut RECT as *mut _, + std::mem::size_of::() as u32, + ); + + // Fall back to GetWindowRect if DwmGetWindowAttribute fails + if result.is_err() { + let _ = GetWindowRect(hwnd, &mut rect); + } + let width = rect.right - rect.left; let height = rect.bottom - rect.top; @@ -97,8 +112,8 @@ pub fn get_target_dimensions(target: &Target) -> (u64, u64) { let monitor = Monitor::from_raw_hmonitor(display.raw_handle.0); ( - monitor.width().unwrap() as u64, - monitor.height().unwrap() as u64, + monitor.width().unwrap_or_default() as u64, + monitor.height().unwrap_or_default() as u64, ) } }