Win32 Taskbar Hooking & Overlay Interop
LocalTelemetry embeds a high-performance GDI+ render surface (NativeWindow) directly into the native Windows taskbar process (Shell_TrayWnd).
Win32 Taskbar Hierarchy & State Machine
The taskbar overlay management is handled inside TaskbarOverlay.cs and TaskbarEmbedder.cs.
Taskbar Embedding Strategies
Implemented in TaskbarEmbedder.cs, LocalTelemetry provides a 2-tier embedding engine to guarantee compatibility across all Windows 10 and 11 builds:
Child-Window Reparenting (IsChildMode)
- Find Taskbar HWND:
FindWindow("Shell_TrayWnd", null)locates the primary taskbar window handle. - Find ReBar / TaskBand:
FindWindowEx(trayHwnd, IntPtr.Zero, "ReBarWindow32", null)retrieves the control container and taskband (MSTaskSwWClass). - Reparent Window (
SetParent): Calls Win32SetParent(overlayHwnd, parentHwnd)to reparent the overlay window as a native child control of the taskbar. - Shrink TaskBand (
ShrinkTaskBand): Dynamically reduces taskband width to reserve dedicated space for the overlay metrics on the taskbar. - Apply Window Styles (
SetWindowLong): SetsWS_CHILD,WS_EX_TOOLWINDOW(hides from Alt+Tab),WS_EX_NOACTIVATE, andWS_EX_LAYERED.
Layered Floating Window Fallback (IsFallback)
- Activated if reparenting fails due to third-party shell software or security policies.
- Restores top-level window styles (
WS_POPUP,WS_EX_TOPMOST) and positions a transparent layered floating window precisely over the taskbar bounding rectangle.
Taskbar Alignment & Coordinate Mathematics
LocalTelemetry dynamically adapts overlay placement based on Windows 11 taskbar alignment:
1. Taskbar Alignment Detection (IsTaskbarCentered)
Inspects user registry configuration:
using var key = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced");
int val = Convert.ToInt32(key?.GetValue("TaskbarAl") ?? 1);
return val == 1; // 1 = Centered, 0 = Left-aligned2. Centered Taskbar Positioning
On centered taskbars, the app icons occupy the center band:
- Left Placement (
left): Anchors relative to the Windows Widgets button edge (_leftWidgetRightEdge + PlacementOffset). - Right Placement (
right): Anchors directly before the system notification area (_trayLeftEdge - Width - PlacementOffset).
3. Left-Aligned Taskbar Positioning
On left-aligned taskbars, app icons start from the Start button and expand toward the right:
Application Band Boundary Detection (
GetAppListRightEdge&GetAppListLeftEdge):- Inspects UIAutomation elements for
Taskbar.TaskListButtonPanelor nativeMSTaskListWClass. - Determines the exact left and right boundaries of running and pinned applications.
- Inspects UIAutomation elements for
Taskbar Space Congestion Detection (
IsTaskbarSpaceConstrained):- Calculates the available horizontal gap (
AvailableSlotWidth) between running app icons and the system tray or widgets. - Sets
IsTaskbarSpaceConstrainedtotruewhen the measured slot is narrower than the overlay width (overlayWidth > availableWidth). - Supplies status to the frontend settings UI via
TaskbarSlotStatusProvider.
- Calculates the available horizontal gap (
Position Next to Apps (
beside_appsorleft):Positions the overlay immediately following the app list:
$$\text{X} = \text{clientAppRight} + \text{PlacementOffset}$$
Position Before System Tray (
right):Positions the overlay immediately before the system notification area:
$$\text{X} = \text{clientRightBoundary} - \text{Width} - \text{PlacementOffset}$$
Boundary Clamping:
- Clamps computed coordinates via
Math.Clamp(x, minX, maxX)to keep the overlay within bounds and prevent visual overlap.
- Clamps computed coordinates via
Deployment Lifecycle State Machine
TaskbarEmbedder.cs tracks overlay attachment health using OverlayDeploymentState:
public OverlayDeploymentState State { get; private set; } = OverlayDeploymentState.Uninitialized;Uninitialized: Overlay is hidden or has not yet completed initial taskbar discovery.Active: Taskbar handle verified and overlay successfully positioned (either as child or layered fallback).Failed: Taskbar handle not found orSetParentcall failed.Recovering: Watchdog detected thatexplorer.exerestarted; attempting re-embedding cycle.
GDI+ Double-Buffered Rendering Engine
Implemented in TaskbarOverlay.cs, TaskbarOverlay inherits from System.Windows.Forms.NativeWindow:
- Renders hardware metrics into an in-memory double-buffered bitmap using GDI+ (
System.Drawing.Graphics). - Caches font families and solid brushes to eliminate memory allocations on high-frequency polling ticks.
- Updates the layered window surface using
UpdateLayeredWindow/SetLayeredWindowAttributes. - When an alert triggers, applies a visual warning tint across the buffer (
rgba(255, 80, 0, 0.24)).
High-DPI Awareness & Scaling
Queries GetDpiForWindow to dynamically scale font rendering, text margins, and line heights for 4K displays and custom DPI scaling settings (100%, 125%, 150%, 175%, 200%+).
Windows Explorer Restart Recovery
When explorer.exe crashes or restarts, all child window handles of Shell_TrayWnd are destroyed by the operating system:
- 5-Second Heartbeat Watchdog (
_watchTimer): A background timer pollsTaskbarEmbedder.FindExplorerTrayWnd()every 5 seconds. If the taskbar window handle changes or is recreated, it immediately triggersOnTaskbarRecreated()on the UI thread:
private void WatchdogTick()
{
IntPtr currentTray = NativeMethods.FindWindow("Shell_TrayWnd", null);
if (currentTray != _lastKnownTray && currentTray != IntPtr.Zero)
{
Log.Info("Explorer restart detected; re-embedding taskbar overlay");
_dispatcher.Invoke(ReembedOverlay);
}
}- State Transition to
Recovering: During re-embedding,Statetransitions toOverlayDeploymentState.Recovering. Once positioning succeeds, it returns toActive.