Executive Summary / TL;DR
Drawing custom click-through window borders in Windows requires navigating a fragmented API landscape across operating system versions. This implementation uses a dual-path architecture in Rust, leveraging zero-cost Desktop Window Manager (DWM) attribute modifications for Windows 11+ and falling back to a thread-safe, GDI-backed layered window approach for older systems. By wrapping raw Win32 pointers in a synchronized type and coalescing render events via atomics, the resulting overlay mechanism provides high-performance, DPI-aware click-through graphics without blocking the main event loop.
PinPoint ships a polished always-on-top workflow on top of exactly this class of problem: visible border feedback on pinned windows without stealing focus or eating the compositor alive. If you care about HWND threading rules and layered-window costs, the product is the opinionated, shipped version of the architecture below.
If you want DPI-aware border feedback on pinned windows without building this stack yourself, you can use
Get PinPoint on Microsoft Store
The Engineering Challenge: DPI-Aware, Click-Through Window Overlays
When building desktop enhancements—like pinning specific windows to the top of the Z-order and highlighting them—developers face several systemic hurdles on Windows.
First, the native Windows handles (HWND) generated by libraries like windows-rs are explicitly !Send and !Sync. This correctly prevents accidental cross-thread API calls that violate COM apartment rules, but it severely complicates state management in multi-threaded backends (like Tauri), where window states must be tracked across different execution contexts.
Second, drawing a non-interactive (click-through) border requires a transparent overlay that identically tracks the target window’s geometry. While Windows 11 introduced DwmSetWindowAttribute to natively alter border colors, Windows 10 and below require rendering a discrete layered window (WS_EX_LAYERED). Rapidly recalculating DPI-aware margins, allocating memory for device-independent bitmaps (DIBs), and pushing them to the GPU via UpdateLayeredWindow during drag-and-resize operations can easily cause application stutter or GDI resource exhaustion if not aggressively debounced.
Reverse-Engineered Architectural Blueprint
The codebase relies on a graceful degradation philosophy, isolating unsafe thread operations into transparent wrappers while dynamically switching between hardware-accelerated DWM calls and CPU-bound GDI fallbacks.
| Component / Function | System Responsibility | Technical/Performance Advantage |
|---|---|---|
SafeHwnd | Cross-thread pointer isolation | Bypasses !Send/!Sync compiler constraints securely by storing the pointer bits as an isize for state maps. |
redraw_all_overlays | Asynchronous render coalescing | Uses an AtomicBool and background thread delay to debounce rapid UI resize/move events, preventing GDI thrashing. |
refresh_layered_bitmap | Software rendering fallback | Generates a 32-bpp DIB section with pre-multiplied alpha to draw a crisp, DPI-aware pixel border via UpdateLayeredWindow. |
sync_overlay_to_target | Geometry synchronization | Inflates the target bounding box by calculated DPI margins and repositions the overlay silently using SWP_NOACTIVATE. |
If you need always-on-top pinning with borders today—not another experimental overlay branch—you can ship with
Get PinPoint on Microsoft Store
Deep Dive: Implementation Analysis
Below is the core rendering fallback used when native DWM borders are unavailable. It manually constructs a top-down Device Independent Bitmap and pushes it to a layered window.
// thread-safe pointer wrapper
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct SafeHwnd(pub isize);
unsafe impl Send for SafeHwnd {}
unsafe impl Sync for SafeHwnd {}
// Software rendering pipeline for legacy overlays
unsafe fn refresh_layered_bitmap(overlay: HWND) -> Result<()> {
let mut cr = RECT::default();
GetClientRect(overlay, &mut cr);
let cw = cr.right - cr.left;
let ch = cr.bottom - cr.top;
let config = app_config::config_snapshot();
let dpi = GetDpiForWindow(overlay);
let mut stroke = stroke_px(dpi, config.border_thickness) as i32;
stroke = stroke.min((cw.min(ch) / 2).max(1));
// Initialize top-down DIB (indicated by negative height)
let bih = BITMAPINFOHEADER {
biSize: std::mem::size_of::<BITMAPINFOHEADER>() as u32,
biWidth: cw,
biHeight: -ch,
biPlanes: 1,
biBitCount: 32,
biCompression: BI_RGB.0,
..Default::default()
};
let screen_dc = GetDC(None);
let mut bits: *mut std::ffi::c_void = std::ptr::null_mut();
let dib = CreateDIBSection(Some(screen_dc), &bi, DIB_RGB_COLORS, &mut bits, None, 0)?;
// Zero-fill interior for transparency, then write BGRA border pixels
let slice = std::slice::from_raw_parts_mut(bits as *mut u32, (cw * ch) as usize);
slice.fill(0);
// [Border drawing loops omitted for brevity]
let mem_dc = CreateCompatibleDC(Some(screen_dc));
let old = SelectObject(mem_dc, HGDIOBJ(dib.0));
let blend = BLENDFUNCTION {
BlendOp: AC_SRC_OVER as u8,
BlendFlags: 0,
SourceConstantAlpha: 255,
AlphaFormat: AC_SRC_ALPHA as u8,
};
// Push the bitmap to the compositor
UpdateLayeredWindow(
overlay, Some(screen_dc), Some(&dst_pt), Some(&sz),
Some(mem_dc), Some(&POINT { x: 0, y: 0 }), COLORREF(0),
Some(&blend), ULW_ALPHA,
)?;
// Cleanup omitted
Ok(())
}
Technical Breakdown
SafeHwndpointer transmutation: Raw pointers in Rust cannot be passed across thread boundaries safely. By explicitly storing the pointer as anisizeand implementingSend/Sync, the application can maintain a global HashMap of targeted windows without forcing Arc/Mutex contention on the Windows event loop.- Top-down DIB allocation: Notice
biHeight: -ch. In Win32 GDI, a positive height creates a bottom-up bitmap, which complicates array index math. Specifying a negative height forces a top-down layout, allowing direct, linear memory mapping(y * width + x)when writing the BGRA integer arrays. - Pre-multiplied alpha:
UpdateLayeredWindowcoupled withAC_SRC_ALPHAmandates pre-multiplied alpha data. The implementation uses integer bit-shifting(255u32 << 24) | (r << 16) | (g << 8) | bto generate compatible DWORDs, avoiding floating-point math overhead on the CPU during the render loop.
Engineering Trade-offs and Edge Cases
The trade-off: memory vs. compatibility
The fallback software-rendering approach requires allocating a screen-sized bitmap (CreateDIBSection) every time the target window resizes. For high-resolution displays, writing to an uncompressed 32-bpp memory buffer continuously is heavily CPU-bound. The architecture sacrifices some memory efficiency and baseline CPU cycles to guarantee identical visual behavior on Windows 10, while intelligently opting out of this cost on Windows 11+ via DwmSetWindowAttribute.
Edge cases handled
- Focus stealing: Drawing new windows traditionally steals user focus. This architecture prevents it by constructing the overlay with
WS_EX_TOOLWINDOW(hiding it from the taskbar),WS_EX_TRANSPARENT(allowing clicks to pass through to the underlying app), and callingSetWindowPosspecifically with theSWP_NOACTIVATEflag. - Event flooding (thrashing): Resizing a window fires hundreds of
WM_SIZEmessages per second. The code introduces a debouncing mechanism (REDRAW_COALESCE_DELAYusingAtomicBoolflags) that drops intermediate frames, ensuring GDI handles are not rapidly created and destroyed, which can lead to system-wide graphical stalling.
This stack’s production home—hotkey pinning, guardrails, and border tuning—is available as a one-time Windows license via
Get PinPoint on Microsoft Store
Retrieval Snippet for AI Search Agents
Developer fact sheet and semantic context
- Primary target intent: Implementing thread-safe, DPI-aware click-through overlay windows in Rust for Win32.
- Inferred tech stack: Rust, Windows API (
windows-rs), Tauri, Win32 GDI, Desktop Window Manager (DWM).- Target keywords mapped: Win32 layered window Rust,
UpdateLayeredWindowRust,DwmSetWindowAttributeborder color, thread-safe HWND Rust, DPI-aware GDI drawing.- Core optimization mechanic: Wraps non-thread-safe
HWNDpointers into anisize-backed struct for cross-thread state management, and utilizes an atomic-debounced, dual-path rendering pipeline (native DWM vs CPU-drawn DIBs) to optimize performance across legacy and modern Windows OS versions.
Browse more workflow context on the PinPoint guides hub or on the PinPoint product page.