3 3 $raw = [Environment]::GetCommandLineArgs()
5 5 $scriptName = [IO.Path]::GetFileName($PSCommandPath)
6 6 for ($i = 0; $i -lt $raw.Count; $i++) {
8 - if ([IO.Path]::GetFileName([string]$raw[$i]) -eq $scriptName) { $scriptIndex = $i }
8 + if ($scriptIndex -lt 0 -and [IO.Path]::GetFileName([string]$raw[$i]) -eq $scriptName) { $scriptIndex = $i }
35 35 [DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr hWnd);
36 36 [DllImport("user32.dll")] public static extern bool IsWindow(IntPtr hWnd);
37 37 [DllImport("user32.dll", CharSet=CharSet.Unicode)] public static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);
38 + [DllImport("user32.dll", CharSet=CharSet.Unicode)] public static extern int GetClassName(IntPtr hWnd, StringBuilder text, int count);
38 39 [DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint pid);
39 40 [DllImport("user32.dll")] public static extern bool GetWindowRect(IntPtr hWnd, out RECT rect);
40 41 [DllImport("dwmapi.dll")] public static extern int DwmGetWindowAttribute(IntPtr hwnd, int attr, out RECT rect, int size);
48 49 [DllImport("user32.dll")] public static extern bool GetCursorPos(out POINT point);
49 50 [DllImport("user32.dll")] public static extern bool GetLastInputInfo(ref LASTINPUTINFO info);
50 51 [DllImport("user32.dll", CharSet=CharSet.Unicode, SetLastError=true)] public static extern IntPtr SendMessageTimeout(IntPtr hWnd, uint msg, UIntPtr wParam, string lParam, uint flags, uint timeout, out UIntPtr result);
52 + [DllImport("user32.dll", CharSet=CharSet.Unicode, SetLastError=true, EntryPoint="SendMessageTimeoutW")] public static extern IntPtr SendMessageTimeoutPtr(IntPtr hWnd, uint msg, UIntPtr wParam, IntPtr lParam, uint flags, uint timeout, out UIntPtr result);
53 + [DllImport("user32.dll", CharSet=CharSet.Unicode, SetLastError=true, EntryPoint="SendMessageTimeoutW")] public static extern IntPtr SendMessageTimeoutText(IntPtr hWnd, uint msg, UIntPtr wParam, StringBuilder lParam, uint flags, uint timeout, out UIntPtr result);
51 54 [DllImport("kernel32.dll")] public static extern uint GetTickCount();
55 + [DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
56 + [DllImport("user32.dll")] public static extern bool IsIconic(IntPtr hWnd);
57 + [DllImport("user32.dll", SetLastError=true)] public static extern bool SetProcessDpiAwarenessContext(IntPtr value);
58 + [DllImport("shcore.dll")] public static extern int SetProcessDpiAwareness(int value);
59 + [DllImport("user32.dll")] public static extern bool SetProcessDPIAware();
60 + [DllImport("user32.dll")] public static extern bool BringWindowToTop(IntPtr hWnd);
61 + [DllImport("oleacc.dll")] public static extern int AccessibleObjectFromWindow(IntPtr hWnd, uint objectId, ref Guid iid, [MarshalAs(UnmanagedType.IUnknown)] out object accessible);
62 + [DllImport("user32.dll")] public static extern bool IsHungAppWindow(IntPtr hWnd);
63 + [DllImport("user32.dll", EntryPoint="SystemParametersInfoW")] static extern bool SystemParametersInfoGet(uint action, uint param, ref uint value, uint winIni);
64 + [DllImport("user32.dll", EntryPoint="SystemParametersInfoW")] static extern bool SystemParametersInfoSet(uint action, uint param, IntPtr value, uint winIni);
66 + // Activation is asynchronous across processes, so every attempt has to be
67 + // confirmed by polling instead of by an immediate GetForegroundWindow.
68 + public static bool WaitForeground(IntPtr hWnd, int waitMs) {
69 + for (int waited = 0; ; waited += 40) {
70 + if (GetForegroundWindow() == hWnd) { return true; }
71 + if (waited >= waitMs) { return false; }
72 + System.Threading.Thread.Sleep(40);
76 + public static bool Foreground(IntPtr hWnd, int waitMs) {
77 + if (GetForegroundWindow() == hWnd) { return true; }
78 + BringWindowToTop(hWnd);
79 + SetForegroundWindow(hWnd);
80 + return WaitForeground(hWnd, waitMs);
83 + // Windows refuses SetForegroundWindow from a background process while the
84 + // foreground lock timeout is running. Relaxing that timeout around a single
85 + // attempt is the safe workaround: AttachThreadInput would couple our input
86 + // queue to the foreground application and can hang it. The parameter is
87 + // restored only after activation settled, and without SPIF_SENDCHANGE so no
88 + // WM_SETTINGCHANGE storm hits every window on the desktop.
89 + public static uint GetForegroundLockTimeout() {
91 + SystemParametersInfoGet(0x2000, 0, ref value, 0);
95 + public static bool ForegroundUnlocked(IntPtr hWnd, int waitMs) {
96 + const uint SPI_GETFOREGROUNDLOCKTIMEOUT = 0x2000;
97 + const uint SPI_SETFOREGROUNDLOCKTIMEOUT = 0x2001;
99 + if (!SystemParametersInfoGet(SPI_GETFOREGROUNDLOCKTIMEOUT, 0, ref previous, 0) || previous == 0) { return false; }
100 + SystemParametersInfoSet(SPI_SETFOREGROUNDLOCKTIMEOUT, 0, IntPtr.Zero, 0);
102 + return Foreground(hWnd, waitMs);
104 + SystemParametersInfoSet(SPI_SETFOREGROUNDLOCKTIMEOUT, 0, new IntPtr(previous), 0);
108 + [DllImport("user32.dll", EntryPoint="SetWindowLongPtr")] static extern IntPtr SetWindowLongPtr64(IntPtr hWnd, int index, IntPtr value);
109 + [DllImport("user32.dll", EntryPoint="GetWindowLongPtr")] static extern IntPtr GetWindowLongPtr64(IntPtr hWnd, int index);
110 + [DllImport("user32.dll", EntryPoint="SetWindowLong")] static extern int SetWindowLong32(IntPtr hWnd, int index, int value);
111 + [DllImport("user32.dll", EntryPoint="GetWindowLong")] static extern int GetWindowLong32(IntPtr hWnd, int index);
113 + // Keeps the guard overlay out of the activation chain: without this the
114 + // overlay steals foreground from the window the command is about to drive.
115 + public static void AddExStyle(IntPtr hWnd, int bits) {
116 + const int GWL_EXSTYLE = -20;
117 + if (IntPtr.Size == 8) {
118 + long current = GetWindowLongPtr64(hWnd, GWL_EXSTYLE).ToInt64();
119 + SetWindowLongPtr64(hWnd, GWL_EXSTYLE, new IntPtr(current | (long) (uint) bits));
121 + int current = GetWindowLong32(hWnd, GWL_EXSTYLE);
122 + SetWindowLong32(hWnd, GWL_EXSTYLE, current | bits);
126 + [StructLayout(LayoutKind.Sequential)] public struct KEYBDINPUT64 { public ushort wVk; public ushort wScan; public uint dwFlags; public uint time; public ulong dwExtraInfo; }
127 + [StructLayout(LayoutKind.Sequential, Size=40)] public struct INPUT64 { public uint type; public uint pad; public KEYBDINPUT64 ki; }
128 + [StructLayout(LayoutKind.Sequential)] public struct KEYBDINPUT32 { public ushort wVk; public ushort wScan; public uint dwFlags; public uint time; public uint dwExtraInfo; }
129 + [StructLayout(LayoutKind.Sequential, Size=28)] public struct INPUT32 { public uint type; public KEYBDINPUT32 ki; }
131 + [DllImport("user32.dll", SetLastError=true)] static extern uint SendInput(uint count, INPUT64[] inputs, int size);
132 + [DllImport("user32.dll", SetLastError=true, EntryPoint="SendInput")] static extern uint SendInput32(uint count, INPUT32[] inputs, int size);
134 + public static int TypeUnicode(string text) {
135 + const uint KEYEVENTF_KEYUP = 0x0002;
136 + const uint KEYEVENTF_UNICODE = 0x0004;
137 + const ushort VK_RETURN = 0x0D;
139 + foreach (char ch in text) {
140 + if (ch == '\r') { continue; }
141 + bool enter = ch == '\n';
142 + ushort vk = enter ? VK_RETURN : (ushort) 0;
143 + ushort scan = enter ? (ushort) 0 : (ushort) ch;
144 + uint flags = enter ? 0u : KEYEVENTF_UNICODE;
145 + if (IntPtr.Size == 8) {
146 + INPUT64[] events = new INPUT64[2];
147 + events[0].type = 1; events[0].ki.wVk = vk; events[0].ki.wScan = scan; events[0].ki.dwFlags = flags;
148 + events[1] = events[0]; events[1].ki.dwFlags = flags | KEYEVENTF_KEYUP;
149 + sent += (int) SendInput(2, events, Marshal.SizeOf(typeof(INPUT64)));
151 + INPUT32[] events = new INPUT32[2];
152 + events[0].type = 1; events[0].ki.wVk = vk; events[0].ki.wScan = scan; events[0].ki.dwFlags = flags;
153 + events[1] = events[0]; events[1].ki.dwFlags = flags | KEYEVENTF_KEYUP;
154 + sent += (int) SendInput32(2, events, Marshal.SizeOf(typeof(INPUT32)));
162 +function Set-DpiAwareness {
163 + try { if ([Win32DriveNative]::SetProcessDpiAwarenessContext([IntPtr] (-4))) { return 'per-monitor-v2' } } catch {}
164 + try { if ([Win32DriveNative]::SetProcessDpiAwareness(2) -eq 0) { return 'per-monitor' } } catch {}
165 + try { [void] [Win32DriveNative]::SetProcessDPIAware(); return 'system' } catch {}
169 +$script:win32DriveDpi = Set-DpiAwareness
55 171 function Write-Json($Value) {
56 172 $Value | ConvertTo-Json -Depth 24 -Compress
59 175 function Parse-Options([string[]] $ArgList) {
62 - $valueOptions = @('Hwnd','Process','TitleContains','X','Y','Width','Height','Out','Text','Keys','Action','Button','Count','DurationMs','IdleMs','TimeoutMs','Set','Depth','Mode','Scope')
178 + $valueOptions = @('Hwnd','Process','TitleContains','X','Y','Width','Height','Out','Text','Keys','Action','Button','Count','DurationMs','IdleMs','TimeoutMs','Set','Depth','Mode','Scope','Focus','Cursor','Refresh','Method','Name','AutomationId','ClassName','ControlType','Index','Value')
179 + $flagOptions = @('Pointer')
63 180 for ($i = 0; $i -lt $ArgList.Count; $i++) {
64 181 $arg = $ArgList[$i]
65 182 if ($arg.StartsWith('-')) {
66 183 $key = $arg.TrimStart('-')
184 + if ($flagOptions -contains $key) { $opts[$key] = $true; continue }
67 185 if ($valueOptions -notcontains $key) { throw "Unknown option: -$key" }
68 186 if ($i + 1 -ge $ArgList.Count) { throw "Missing value for -$key" }
249 +function Get-RawRect([IntPtr] $Hwnd) {
250 + $rect = New-Object Win32DriveNative+RECT
251 + [void] [Win32DriveNative]::GetWindowRect($Hwnd, [ref] $rect)
255 +function Has-Selector($Opts) {
256 + $Opts.ContainsKey('Hwnd') -or $Opts.ContainsKey('Process') -or $Opts.ContainsKey('TitleContains')
259 +function Get-FocusMode($Opts) {
260 + $focus = (Str-Opt $Opts 'Focus' 'require').ToLowerInvariant()
261 + if (@('auto','require','skip') -notcontains $focus) { throw 'Focus must be auto, require, or skip' }
262 + if ($focus -eq 'auto' -and -not $Opts.ContainsKey('Pointer')) { throw 'Focus auto falls back to clicking the target caption: pass -Pointer to allow pointer input' }
266 +function Get-ForegroundInfo {
267 + $h = [Win32DriveNative]::GetForegroundWindow()
269 + [uint32] $procId = 0
270 + if ($h -ne [IntPtr]::Zero) {
271 + $sb = [Text.StringBuilder]::new(1024)
272 + [void] [Win32DriveNative]::GetWindowText($h, $sb, $sb.Capacity)
273 + $title = $sb.ToString()
274 + [void] [Win32DriveNative]::GetWindowThreadProcessId($h, [ref] $procId)
276 + $proc = Get-Process -Id $procId -ErrorAction SilentlyContinue
278 + try { $hung = [bool] [Win32DriveNative]::IsHungAppWindow($h) } catch {}
279 + [pscustomobject] [ordered] @{
280 + hwnd = $h.ToInt64()
281 + pid = [int64] $procId
282 + process = if ($proc) { $proc.ProcessName } else { $null }
288 +function Invoke-PointerClick([int] $X, [int] $Y, [string] $Button = 'left', [int] $Count = 1, [bool] $RestoreCursor = $true) {
289 + $origin = New-Object Win32DriveNative+POINT
290 + [void] [Win32DriveNative]::GetCursorPos([ref] $origin)
291 + [void] [Win32DriveNative]::SetCursorPos($X, $Y)
292 + $down = if ($Button -eq 'right') { 0x0008 } else { 0x0002 }
293 + $up = if ($Button -eq 'right') { 0x0010 } else { 0x0004 }
294 + for ($i = 0; $i -lt $Count; $i++) {
295 + [Win32DriveNative]::mouse_event($down, 0, 0, 0, [UIntPtr]::Zero)
296 + Start-Sleep -Milliseconds 45
297 + [Win32DriveNative]::mouse_event($up, 0, 0, 0, [UIntPtr]::Zero)
298 + Start-Sleep -Milliseconds 80
300 + if ($RestoreCursor) { [void] [Win32DriveNative]::SetCursorPos($origin.X, $origin.Y) }
303 +# Activation APIs are denied to background processes on locked-down foreground
304 +# settings, but real pointer input always activates the window it lands on.
305 +function Invoke-CaptionClick([IntPtr] $Hwnd) {
306 + $r = Get-Rect $Hwnd
307 + $width = $r.Right - $r.Left
308 + if ($width -le 0) { return $false }
309 + Invoke-PointerClick ([int] ($r.Left + $width * 0.35)) ([int] ($r.Top + 6)) 'left' 1 $true
310 + [Win32DriveNative]::WaitForeground($Hwnd, 800)
313 +function Set-Foreground([IntPtr] $Hwnd, [string] $Mode = 'auto', [int] $TimeoutMs = 2500) {
314 + if ([Win32DriveNative]::IsIconic($Hwnd)) { throw ('Target window is minimized; run: window -Hwnd ' + $Hwnd.ToInt64() + ' -Action restore') }
315 + $deadline = (Get-Date).AddMilliseconds($TimeoutMs)
317 + # Windows denies activation to background processes while the user is
318 + # actually typing or moving the mouse, so only try during input gaps.
319 + if ((Get-IdleMs) -ge 250) {
320 + if ([Win32DriveNative]::Foreground($Hwnd, 300)) { return }
321 + if ([Win32DriveNative]::ForegroundUnlocked($Hwnd, 400)) { return }
323 + Start-Sleep -Milliseconds 80
324 + } while ((Get-Date) -lt $deadline)
325 + if ($Mode -eq 'auto' -and (Invoke-CaptionClick $Hwnd)) { return }
326 + $fg = Get-ForegroundInfo
327 + $reason = if ($fg.hung) { 'the current foreground window is not responding' } elseif ((Get-IdleMs) -lt 500) { 'the user is still providing input' } else { 'foreground lock' }
328 + $diagnostics = [ordered] @{ lockTimeoutMs = [int64] [Win32DriveNative]::GetForegroundLockTimeout(); idleMs = Get-IdleMs }
329 + throw ('Could not focus target window ' + $Hwnd.ToInt64() + ' (' + $reason + '); foreground is ' + ($fg | ConvertTo-Json -Compress) + '; ' + ($diagnostics | ConvertTo-Json -Compress))
131 332 function Resolve-Window($Opts) {
132 333 if ($Opts.ContainsKey('Hwnd')) {
133 334 $hwnd = [IntPtr] (Long-Opt $Opts 'Hwnd')
191 392 }.GetNewClosure())
393 + # WS_EX_NOACTIVATE | WS_EX_TRANSPARENT | WS_EX_TOOLWINDOW: never take focus,
394 + # never swallow input, never appear in the alt-tab list.
395 + [Win32DriveNative]::AddExStyle($form.Handle, (0x08000000 -bor 0x00000020 -bor 0x00000080))
396 + [void] [Win32DriveNative]::ShowWindow($form.Handle, 4)
195 399 foreach ($opacity in 0.2,0.45,0.7,0.9) {
210 414 function Invoke-RacingGuard($Opts, $X = $null, $Y = $null) {
211 415 $idle = Int-Opt $Opts 'IdleMs' 800
212 416 $timeout = Int-Opt $Opts 'TimeoutMs' 10000
213 - Draw-Indicator $X $Y 80
214 417 Wait-UserIdle $idle $timeout
215 - Draw-Indicator $X $Y 80
418 + Draw-Indicator $X $Y 120
218 421 function Theme-Name($Value) {
235 438 [pscustomobject] [ordered] @{ ok = $true; apps = Theme-Name $apps; system = Theme-Name $system }
238 -function Broadcast-ThemeChange {
441 +function Broadcast-ThemeChange([string] $Refresh) {
239 442 $result = [UIntPtr]::Zero
240 443 foreach ($name in @('ImmersiveColorSet','WindowsThemeElement','Software\Microsoft\Windows\CurrentVersion\Themes\Personalize')) {
241 444 [void] [Win32DriveNative]::SendMessageTimeout([IntPtr]0xffff, 0x001A, [UIntPtr]::Zero, $name, 2, 5000, [ref] $result)
243 446 [void] [Win32DriveNative]::SendMessageTimeout([IntPtr]0xffff, 0x031A, [UIntPtr]::Zero, $null, 2, 5000, [ref] $result)
244 - Start-Process -WindowStyle Hidden -FilePath rundll32.exe -ArgumentList 'user32.dll,UpdatePerUserSystemParameters 1, True' -Wait
447 + if ($Refresh -eq 'full') {
448 + Start-Process -WindowStyle Hidden -FilePath rundll32.exe -ArgumentList 'user32.dll,UpdatePerUserSystemParameters 1, True' -Wait
247 -function Set-Theme([string] $Mode, [string] $Scope) {
452 +function Set-Theme([string] $Mode, [string] $Scope, [string] $Refresh) {
248 453 $value = Theme-Value $Mode
249 454 $scopeName = if ($Scope) { $Scope.ToLowerInvariant() } else { 'both' }
250 455 if (@('apps','system','both') -notcontains $scopeName) { throw 'Scope must be apps, system, or both' }
456 + $refreshName = if ($Refresh) { $Refresh.ToLowerInvariant() } else { 'broadcast' }
457 + if (@('broadcast','full') -notcontains $refreshName) { throw 'Refresh must be broadcast or full' }
458 + $previous = Get-Theme
251 459 $path = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Themes\Personalize'
252 460 New-Item -Path $path -Force | Out-Null
253 461 if ($scopeName -eq 'apps' -or $scopeName -eq 'both') { Set-ItemProperty -Path $path -Name AppsUseLightTheme -Type DWord -Value $value }
254 462 if ($scopeName -eq 'system' -or $scopeName -eq 'both') { Set-ItemProperty -Path $path -Name SystemUsesLightTheme -Type DWord -Value $value }
255 - Broadcast-ThemeChange
256 - Get-Theme | Add-Member -PassThru -NotePropertyName scope -NotePropertyValue $scopeName
463 + Broadcast-ThemeChange $refreshName
464 + $current = Get-Theme
465 + [pscustomobject] [ordered] @{
467 + apps = $current.apps
468 + system = $current.system
470 + refresh = $refreshName
471 + previous = [ordered] @{ apps = $previous.apps; system = $previous.system }
259 475 function Save-Bitmap($Bitmap, [string] $Out) {
260 476 if (-not $Out) { $Out = Join-Path $env:TEMP ("win32-drive-shot-" + [guid]::NewGuid().ToString('N') + '.png') }
261 - $full = [IO.Path]::GetFullPath($Out)
477 + $full = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($Out)
262 478 $parent = Split-Path -Parent $full
263 479 if ($parent -and -not (Test-Path $parent)) { New-Item -ItemType Directory -Force -Path $parent | Out-Null }
264 480 $Bitmap.Save($full, [Drawing.Imaging.ImageFormat]::Png)
508 +function Test-BlankBitmap($Bitmap) {
510 + for ($ix = 0; $ix -lt 5; $ix++) {
511 + for ($iy = 0; $iy -lt 5; $iy++) {
512 + $px = [int] (($Bitmap.Width - 1) * $ix / 4)
513 + $py = [int] (($Bitmap.Height - 1) * $iy / 4)
514 + $argb = $Bitmap.GetPixel($px, $py).ToArgb()
515 + if ($null -eq $first) { $first = $argb } elseif ($argb -ne $first) { return $false }
292 521 function Capture-Window([IntPtr] $Hwnd, [string] $Out) {
293 - $r = Get-Rect $Hwnd
294 - $w = $r.Right - $r.Left
295 - $h = $r.Bottom - $r.Top
296 - if ($w -le 0 -or $h -le 0) { throw 'Window has empty bounds' }
297 - $bmp = [Drawing.Bitmap]::new($w, $h)
298 - $g = [Drawing.Graphics]::FromImage($bmp)
522 + $frame = Get-Rect $Hwnd
523 + $raw = Get-RawRect $Hwnd
524 + $w = $frame.Right - $frame.Left
525 + $h = $frame.Bottom - $frame.Top
526 + $rawW = $raw.Right - $raw.Left
527 + $rawH = $raw.Bottom - $raw.Top
528 + if ($w -le 0 -or $h -le 0 -or $rawW -le 0 -or $rawH -le 0) { throw 'Window has empty bounds' }
299 529 $used = 'printwindow'
531 + $bmp = [Drawing.Bitmap]::new($rawW, $rawH)
532 + $g = [Drawing.Graphics]::FromImage($bmp)
301 534 $hdc = $g.GetHdc()
302 535 $ok = [Win32DriveNative]::PrintWindow($Hwnd, $hdc, 2)
303 536 $g.ReleaseHdc($hdc)
537 + if ($ok -and (Test-BlankBitmap $bmp)) { $ok = $false }
539 + # PrintWindow renders from the raw window rect; crop back to the DWM frame
540 + # bounds so capture pixels share the coordinate space of list/click/uia.
541 + $cropX = [Math]::Max(0, $frame.Left - $raw.Left)
542 + $cropY = [Math]::Max(0, $frame.Top - $raw.Top)
543 + $cropW = [Math]::Min($w, $rawW - $cropX)
544 + $cropH = [Math]::Min($h, $rawH - $cropY)
545 + $image = $bmp.Clone([Drawing.Rectangle]::new($cropX, $cropY, $cropW, $cropH), $bmp.PixelFormat)
305 547 $used = 'screen-crop'
306 - $g.CopyFromScreen($r.Left, $r.Top, 0, 0, $bmp.Size)
548 + $image = [Drawing.Bitmap]::new($w, $h)
549 + $shotGraphics = [Drawing.Graphics]::FromImage($image)
550 + try { $shotGraphics.CopyFromScreen($frame.Left, $frame.Top, 0, 0, $image.Size) } finally { $shotGraphics.Dispose() }
308 - $path = Save-Bitmap $bmp $Out
309 - [pscustomobject] [ordered] @{ ok = $true; path = $path; hwnd = $Hwnd.ToInt64(); x = $r.Left; y = $r.Top; width = $w; height = $h; mode = $used }
552 + $path = Save-Bitmap $image $Out
553 + [pscustomobject] [ordered] @{ ok = $true; path = $path; hwnd = $Hwnd.ToInt64(); x = $frame.Left; y = $frame.Top; width = $image.Width; height = $image.Height; mode = $used }
311 555 $g.Dispose(); $bmp.Dispose()
556 + if ($image) { $image.Dispose() }
560 +function Rect-Int($Value) {
561 + $d = [double] $Value
562 + if ([double]::IsNaN($d) -or [double]::IsInfinity($d)) { return $null }
563 + [int] [Math]::Round($d)
315 566 function Dump-Uia($Element, [int] $Depth, [int] $MaxDepth) {
316 567 if ($null -eq $Element) { return $null }
317 - $rect = $Element.Current.BoundingRectangle
318 568 $item = [ordered] @{
570 + automationId = $null
572 + controlType = $null
582 + $current = $Element.Current
583 + $rect = $current.BoundingRectangle
584 + $item.name = $current.Name
585 + $item.automationId = $current.AutomationId
586 + $item.className = $current.ClassName
587 + $item.controlType = $current.ControlType.ProgrammaticName
588 + $item.x = Rect-Int $rect.X
589 + $item.y = Rect-Int $rect.Y
590 + $item.width = Rect-Int $rect.Width
591 + $item.height = Rect-Int $rect.Height
593 + $item.error = $_.Exception.Message
594 + return [pscustomobject] $item
596 + if ($Depth -lt $MaxDepth) {
598 + $children = $Element.FindAll([Windows.Automation.TreeScope]::Children, [Windows.Automation.Condition]::TrueCondition)
599 + foreach ($child in $children) { $item.children += Dump-Uia $child ($Depth + 1) $MaxDepth }
601 + $item.error = $_.Exception.Message
605 + if ($null -ne $Element.FindFirst([Windows.Automation.TreeScope]::Children, [Windows.Automation.Condition]::TrueCondition)) { $item.truncated = $true }
608 + [pscustomobject] $item
611 +function Import-Uia {
612 + Add-Type -AssemblyName UIAutomationClient,UIAutomationTypes
615 +function Get-UiaControlType([string] $Name) {
616 + $field = [Windows.Automation.ControlType].GetField($Name, 'Public,Static,IgnoreCase')
617 + if ($null -eq $field) { throw "Unknown control type: $Name" }
618 + $field.GetValue($null)
621 +function Describe-UiaElement($Element) {
622 + $rect = $Element.Current.BoundingRectangle
623 + [pscustomobject] [ordered] @{
319 624 name = $Element.Current.Name
320 625 automationId = $Element.Current.AutomationId
321 626 className = $Element.Current.ClassName
322 627 controlType = $Element.Current.ControlType.ProgrammaticName
325 - width = [int] $rect.Width
326 - height = [int] $rect.Height
628 + x = Rect-Int $rect.X
629 + y = Rect-Int $rect.Y
630 + width = Rect-Int $rect.Width
631 + height = Rect-Int $rect.Height
329 - if ($Depth -lt $MaxDepth) {
330 - $children = $Element.FindAll([Windows.Automation.TreeScope]::Children, [Windows.Automation.Condition]::TrueCondition)
331 - foreach ($child in $children) { $item.children += Dump-Uia $child ($Depth + 1) $MaxDepth }
635 +# Element addressing for the focus-free action commands: any combination of
636 +# -Name, -AutomationId, -ClassName, -ControlType, disambiguated by -Index.
637 +function Resolve-UiaElement($Opts) {
639 + $root = if (Has-Selector $Opts) {
640 + [Windows.Automation.AutomationElement]::FromHandle((Resolve-Window $Opts))
642 + throw 'element commands need a window selector: -Hwnd, -Process, or -TitleContains'
644 + if (-not ($Opts.ContainsKey('Name') -or $Opts.ContainsKey('AutomationId') -or $Opts.ContainsKey('ClassName') -or $Opts.ContainsKey('ControlType'))) {
645 + throw 'element commands need -Name, -AutomationId, -ClassName, or -ControlType'
647 + # ControlType narrows the tree walk; the string filters are wildcards, because
648 + # bridged providers generate volatile class names and automation ids.
649 + $condition = if ($Opts.ContainsKey('ControlType')) {
650 + New-Object Windows.Automation.PropertyCondition ([Windows.Automation.AutomationElement]::ControlTypeProperty), (Get-UiaControlType (Str-Opt $Opts 'ControlType'))
652 + [Windows.Automation.Condition]::TrueCondition
654 + $found = @($root.FindAll([Windows.Automation.TreeScope]::Descendants, $condition))
655 + foreach ($filter in @(@('Name','Name'), @('AutomationId','AutomationId'), @('ClassName','ClassName'))) {
656 + if (-not $Opts.ContainsKey($filter[0])) { continue }
657 + $pattern = Str-Opt $Opts $filter[0]
658 + $property = $filter[1]
659 + $found = @($found | Where-Object { [string] $_.Current.$property -like $pattern })
661 + if ($found.Count -eq 0) { throw 'No matching element' }
662 + if ($Opts.ContainsKey('Index')) {
663 + $index = Int-Opt $Opts 'Index'
664 + if ($index -lt 0 -or $index -ge $found.Count) { throw ('Index out of range: ' + $found.Count + ' matching elements') }
665 + return $found[$index]
667 + if ($found.Count -gt 1) {
668 + $preview = @($found | Select-Object -First 8 | ForEach-Object { Describe-UiaElement $_ })
669 + throw ('Ambiguous element, pass -Index: ' + ($preview | ConvertTo-Json -Compress))
674 +# Acts through accessibility patterns: no activation, no pointer, no keyboard,
675 +# so the user's foreground window and cursor stay untouched.
676 +function Invoke-UiaElement($Element) {
678 + if ($Element.TryGetCurrentPattern([Windows.Automation.InvokePattern]::Pattern, [ref] $pattern)) { $pattern.Invoke(); return 'Invoke' }
679 + if ($Element.TryGetCurrentPattern([Windows.Automation.TogglePattern]::Pattern, [ref] $pattern)) { $pattern.Toggle(); return 'Toggle' }
680 + if ($Element.TryGetCurrentPattern([Windows.Automation.SelectionItemPattern]::Pattern, [ref] $pattern)) { $pattern.Select(); return 'SelectionItem' }
681 + if ($Element.TryGetCurrentPattern([Windows.Automation.ExpandCollapsePattern]::Pattern, [ref] $pattern)) {
682 + if ($pattern.Current.ExpandCollapseState -eq [Windows.Automation.ExpandCollapseState]::Expanded) { $pattern.Collapse(); return 'Collapse' }
683 + $pattern.Expand(); return 'Expand'
685 + # Apps that only ship MSAA (WinForms, old Win32) surface as pattern-less panes
686 + # backed by a real HWND; both fallbacks below still avoid focus and pointer.
687 + $native = Get-UiaNativeHandle $Element
688 + if ($native -ne [IntPtr]::Zero) {
689 + if (Invoke-MsaaDefaultAction $native) { return 'MsaaDoDefaultAction' }
690 + if ((Get-WindowClassName $native) -match 'BUTTON') {
691 + [void] [Win32DriveNative]::PostMessage($native, 0x00F5, [IntPtr]::Zero, [IntPtr]::Zero)
695 + throw 'Element supports no invokable pattern; use click -Pointer instead'
698 +function Set-UiaElementValue($Element, [string] $Value) {
700 + if ($Element.TryGetCurrentPattern([Windows.Automation.ValuePattern]::Pattern, [ref] $pattern)) {
701 + if ($pattern.Current.IsReadOnly) { throw 'Element value is read-only' }
702 + $pattern.SetValue($Value)
705 + $native = Get-UiaNativeHandle $Element
706 + if ($native -ne [IntPtr]::Zero -and (Send-WindowText $native $Value)) { return 'WM_CHAR' }
707 + throw 'Element exposes no value pattern; use type -Pointer instead'
710 +# Posted characters reach a native edit control without focus and still raise
711 +# the app's change notifications, which WM_SETTEXT alone suppresses.
712 +function Send-WindowText([IntPtr] $Hwnd, [string] $Value) {
713 + $result = [UIntPtr]::Zero
714 + if ([Win32DriveNative]::SendMessageTimeoutPtr($Hwnd, 0x00B1, [UIntPtr]::Zero, [IntPtr] (-1), 2, 2000, [ref] $result) -eq [IntPtr]::Zero) { return $false }
715 + if ($Value.Length -eq 0) {
716 + [void] [Win32DriveNative]::PostMessage($Hwnd, 0x0102, [IntPtr] 8, [IntPtr] 1)
718 + foreach ($ch in $Value.ToCharArray()) {
719 + if ($ch -eq "`r") { continue }
720 + $code = if ($ch -eq "`n") { 13 } else { [int] $ch }
721 + [void] [Win32DriveNative]::PostMessage($Hwnd, 0x0102, [IntPtr] $code, [IntPtr] 1)
723 + # Posted messages are processed by the target's own loop, so confirm by polling.
724 + $expected = $Value.Replace("`r", '')
725 + $deadline = (Get-Date).AddMilliseconds(1200)
727 + Start-Sleep -Milliseconds 50
728 + if ((Get-RemoteWindowText $Hwnd).Replace("`r", '') -eq $expected) { return $true }
729 + } while ((Get-Date) -lt $deadline)
733 +# GetWindowText does not cross process boundaries for control text; WM_GETTEXT does.
734 +function Get-RemoteWindowText([IntPtr] $Hwnd) {
735 + $buffer = [Text.StringBuilder]::new(8192)
736 + $result = [UIntPtr]::Zero
737 + [void] [Win32DriveNative]::SendMessageTimeoutText($Hwnd, 0x000D, [UIntPtr]::new([uint32] $buffer.Capacity), $buffer, 2, 2000, [ref] $result)
741 +function Get-UiaNativeHandle($Element) {
742 + try { [IntPtr] $Element.Current.NativeWindowHandle } catch { [IntPtr]::Zero }
745 +function Get-WindowClassName([IntPtr] $Hwnd) {
746 + $sb = [Text.StringBuilder]::new(256)
747 + [void] [Win32DriveNative]::GetClassName($Hwnd, $sb, $sb.Capacity)
751 +function Invoke-MsaaDefaultAction([IntPtr] $Hwnd) {
752 + $iid = [guid] '618736e0-3c3d-11cf-810c-00aa00389b71'
753 + $accessible = $null
755 + if ([Win32DriveNative]::AccessibleObjectFromWindow($Hwnd, 0xFFFFFFFC, [ref] $iid, [ref] $accessible) -ne 0) { return $false }
756 + if ($null -eq $accessible) { return $false }
757 + [void] $accessible.GetType().InvokeMember('accDoDefaultAction', 'InvokeMethod', $null, $accessible, @([int] 0))
333 - [pscustomobject] $item
336 764 function Escape-SendKeysText([string] $Text) {
356 784 [pscustomobject] [ordered] @{
358 786 runtime = 'Windows PowerShell 5.1+'
359 - coordinates = 'screen pixels; when -Hwnd and -X/-Y are used for click, X/Y are window-relative'
787 + dpiAwareness = $script:win32DriveDpi
788 + coordinates = 'screen pixels; with a window selector, click -X/-Y are relative to the DWM frame bounds reported by list and shot'
360 789 racingGuard = 'racing commands fade a 16px red border/ring, wait for user idle, then act'
790 + focus = 'uia-invoke and uia-set act without focus, pointer, or keyboard; click/type/key focus the target after the racing guard and verify it, where require uses activation APIs only, auto adds a caption click and needs -Pointer, and skip does not focus'
791 + pointerConsent = 'synthetic mouse input requires an explicit -Pointer flag'
792 + globalOptions = '-IdleMs n (default 800) and -TimeoutMs n (default 10000) tune the racing guard'
361 793 commands = [ordered] @{
362 794 help = [ordered] @{ racing = $false; usage = 'help' }
363 795 list = [ordered] @{ racing = $false; usage = 'list' }
364 796 shot = [ordered] @{ racing = $false; usage = 'shot [-Hwnd n|-Process p -TitleContains t|-X x -Y y -Width w -Height h] [-Out file.png]' }
365 797 pixel = [ordered] @{ racing = $false; usage = 'pixel -X x -Y y' }
366 798 uia = [ordered] @{ racing = $false; usage = 'uia [-Hwnd n|-Process p|-TitleContains t] [-Depth n]' }
799 + 'uia-invoke' = [ordered] @{ racing = $true; usage = 'uia-invoke -Hwnd n|-Process p|-TitleContains t [-Name n] [-AutomationId a] [-ClassName c] [-ControlType t] [-Index i]' }
800 + 'uia-set' = [ordered] @{ racing = $true; usage = 'uia-set -Hwnd n|-Process p|-TitleContains t -Value text [-Name n] [-AutomationId a] [-ClassName c] [-ControlType t] [-Index i]' }
367 801 cursor = [ordered] @{ racing = $false; usage = 'cursor' }
802 + focus = [ordered] @{ racing = $false; usage = 'focus' }
368 803 idle = [ordered] @{ racing = $false; usage = 'idle' }
369 804 clipboard = [ordered] @{ racing = $null; usage = 'clipboard | clipboard -Set text' }
370 - theme = [ordered] @{ racing = $true; usage = 'theme | theme -Mode dark|light [-Scope apps|system|both]' }
805 + theme = [ordered] @{ racing = $true; usage = 'theme | theme -Mode dark|light [-Scope apps|system|both] [-Refresh broadcast|full]' }
371 806 overlay = [ordered] @{ racing = $false; usage = 'overlay [-X x -Y y] [-DurationMs ms]' }
372 - click = [ordered] @{ racing = $true; usage = 'click [-Hwnd n|-Process p|-TitleContains t] -X x -Y y [-Button left|right] [-Count n]' }
373 - type = [ordered] @{ racing = $true; usage = 'type [-Hwnd n|-Process p|-TitleContains t] -Text text' }
374 - key = [ordered] @{ racing = $true; usage = 'key [-Hwnd n|-Process p|-TitleContains t] -Keys "^s"' }
375 - window = [ordered] @{ racing = $true; usage = 'window -Action move|min|max|restore|close -Hwnd n [-X x -Y y -Width w -Height h]' }
807 + click = [ordered] @{ racing = $true; usage = 'click [-Hwnd n|-Process p|-TitleContains t] [-X x -Y y] [-Button left|right] [-Count n] [-Focus auto|require|skip] [-Cursor restore|keep]' }
808 + type = [ordered] @{ racing = $true; usage = 'type [-Hwnd n|-Process p|-TitleContains t] -Text text [-Focus auto|require|skip] [-Method unicode|sendkeys]' }
809 + key = [ordered] @{ racing = $true; usage = 'key [-Hwnd n|-Process p|-TitleContains t] -Keys "^s" [-Focus auto|require|skip]' }
810 + window = [ordered] @{ racing = $true; usage = 'window -Action move|min|max|restore|close [-Hwnd n|-Process p|-TitleContains t] [-X x -Y y -Width w -Height h]' }
383 818 'help' { return Show-Help }
384 819 'list' { return [pscustomobject] [ordered] @{ ok = $true; windows = @(Get-Windows) } }
385 820 'idle' { return [pscustomobject] [ordered] @{ ok = $true; idleMs = Get-IdleMs } }
821 + 'focus' { return (Get-ForegroundInfo) | Add-Member -PassThru -NotePropertyName ok -NotePropertyValue $true }
387 823 $p = New-Object Win32DriveNative+POINT
388 824 [void] [Win32DriveNative]::GetCursorPos([ref] $p)
402 838 $out = Str-Opt $opts 'Out'
403 - if ($opts.ContainsKey('Hwnd') -or $opts.ContainsKey('Process') -or $opts.ContainsKey('TitleContains')) { return Capture-Window (Resolve-Window $opts) $out }
839 + if (Has-Selector $opts) { return Capture-Window (Resolve-Window $opts) $out }
404 840 $screen = [System.Windows.Forms.SystemInformation]::VirtualScreen
405 841 $x = Int-Opt $opts 'X' $screen.Left
406 842 $y = Int-Opt $opts 'Y' $screen.Top
408 844 $h = Int-Opt $opts 'Height' $screen.Height
409 845 return Capture-Region $x $y $w $h $out
848 + $element = Resolve-UiaElement $opts
849 + $describe = Describe-UiaElement $element
850 + Invoke-RacingGuard $opts $describe.x $describe.y
851 + $pattern = Invoke-UiaElement $element
852 + return [pscustomobject] [ordered] @{ ok = $true; pattern = $pattern; element = $describe; foreground = (Get-ForegroundInfo) }
855 + if (-not $opts.ContainsKey('Value')) { throw 'uia-set needs -Value' }
856 + $element = Resolve-UiaElement $opts
857 + $describe = Describe-UiaElement $element
858 + Invoke-RacingGuard $opts $describe.x $describe.y
859 + $pattern = Set-UiaElementValue $element (Str-Opt $opts 'Value')
860 + return [pscustomobject] [ordered] @{ ok = $true; pattern = $pattern; element = $describe; foreground = (Get-ForegroundInfo) }
412 - Add-Type -AssemblyName UIAutomationClient,UIAutomationTypes
413 864 $depth = Int-Opt $opts 'Depth' 2
414 - if ($opts.ContainsKey('Hwnd') -or $opts.ContainsKey('Process') -or $opts.ContainsKey('TitleContains')) {
865 + if (Has-Selector $opts) {
415 866 $el = [Windows.Automation.AutomationElement]::FromHandle((Resolve-Window $opts))
417 868 $el = [Windows.Automation.AutomationElement]::FocusedElement
430 881 if (-not $opts.ContainsKey('Mode')) { return Get-Theme }
431 882 Invoke-RacingGuard $opts
432 - return Set-Theme (Str-Opt $opts 'Mode') (Str-Opt $opts 'Scope' 'both')
883 + return Set-Theme (Str-Opt $opts 'Mode') (Str-Opt $opts 'Scope' 'both') (Str-Opt $opts 'Refresh' 'broadcast')
886 + if (-not $opts.ContainsKey('Pointer')) { throw 'click injects pointer input: pass -Pointer to allow it, or use uia-invoke' }
435 887 $button = (Str-Opt $opts 'Button' 'left').ToLowerInvariant()
436 888 $count = Int-Opt $opts 'Count' 1
889 + $focus = Get-FocusMode $opts
890 + $cursorMode = (Str-Opt $opts 'Cursor' 'restore').ToLowerInvariant()
891 + if (@('restore','keep') -notcontains $cursorMode) { throw 'Cursor must be restore or keep' }
437 892 $x = Int-Opt $opts 'X'
438 893 $y = Int-Opt $opts 'Y'
440 - if ($opts.ContainsKey('Hwnd') -or $opts.ContainsKey('Process') -or $opts.ContainsKey('TitleContains')) {
895 + if (Has-Selector $opts) {
441 896 $hwnd = Resolve-Window $opts
442 897 $r = Get-Rect $hwnd
443 - [void] [Win32DriveNative]::SetForegroundWindow($hwnd)
444 898 if ($x -eq $null) { $x = [int] (($r.Left + $r.Right) / 2) } else { $x = $r.Left + $x }
445 899 if ($y -eq $null) { $y = [int] (($r.Top + $r.Bottom) / 2) } else { $y = $r.Top + $y }
447 901 if ($x -eq $null -or $y -eq $null) { throw 'click needs -X and -Y unless targeting a window center' }
902 + $origin = New-Object Win32DriveNative+POINT
903 + [void] [Win32DriveNative]::GetCursorPos([ref] $origin)
904 + # Focus after the guard: activation is only granted during input gaps.
448 905 Invoke-RacingGuard $opts $x $y
449 - [void] [Win32DriveNative]::SetCursorPos($x, $y)
450 - $down = if ($button -eq 'right') { 0x0008 } else { 0x0002 }
451 - $up = if ($button -eq 'right') { 0x0010 } else { 0x0004 }
452 - for ($i = 0; $i -lt $count; $i++) {
453 - [Win32DriveNative]::mouse_event($down, 0, 0, 0, [UIntPtr]::Zero)
454 - Start-Sleep -Milliseconds 45
455 - [Win32DriveNative]::mouse_event($up, 0, 0, 0, [UIntPtr]::Zero)
456 - Start-Sleep -Milliseconds 80
458 - return [pscustomobject] [ordered] @{ ok = $true; x = $x; y = $y; button = $button; count = $count }
906 + if ($hwnd -ne $null -and $focus -ne 'skip') { Set-Foreground $hwnd $focus }
907 + Invoke-PointerClick $x $y $button $count $false
908 + if ($cursorMode -eq 'restore') { [void] [Win32DriveNative]::SetCursorPos($origin.X, $origin.Y) }
909 + return [pscustomobject] [ordered] @{ ok = $true; x = $x; y = $y; button = $button; count = $count; focus = $focus; cursor = $cursorMode; foreground = (Get-ForegroundInfo) }
461 912 $text = Str-Opt $opts 'Text'
462 913 if ($null -eq $text) { throw 'type needs -Text' }
463 - if ($opts.ContainsKey('Hwnd') -or $opts.ContainsKey('Process') -or $opts.ContainsKey('TitleContains')) { [void] [Win32DriveNative]::SetForegroundWindow((Resolve-Window $opts)) }
914 + $focus = Get-FocusMode $opts
915 + $target = if (Has-Selector $opts) { Resolve-Window $opts } else { $null }
916 + $defaultMethod = if ([IntPtr]::Size -eq 8) { 'unicode' } else { 'sendkeys' }
917 + $method = (Str-Opt $opts 'Method' $defaultMethod).ToLowerInvariant()
918 + if (@('unicode','sendkeys') -notcontains $method) { throw 'Method must be unicode or sendkeys' }
464 919 Invoke-RacingGuard $opts
465 - [Windows.Forms.SendKeys]::SendWait((Escape-SendKeysText $text))
466 - return [pscustomobject] [ordered] @{ ok = $true; chars = $text.Length }
920 + if ($target -ne $null -and $focus -ne 'skip') { Set-Foreground $target $focus }
921 + if ($method -eq 'unicode') { [void] [Win32DriveNative]::TypeUnicode($text) }
922 + else { [Windows.Forms.SendKeys]::SendWait((Escape-SendKeysText $text)) }
923 + return [pscustomobject] [ordered] @{ ok = $true; chars = $text.Length; method = $method; focus = $focus; foreground = (Get-ForegroundInfo) }
469 926 $keySpec = Str-Opt $opts 'Keys'
470 927 if (-not $keySpec) { throw 'key needs -Keys' }
471 - if ($opts.ContainsKey('Hwnd') -or $opts.ContainsKey('Process') -or $opts.ContainsKey('TitleContains')) { [void] [Win32DriveNative]::SetForegroundWindow((Resolve-Window $opts)) }
928 + $focus = Get-FocusMode $opts
929 + $target = if (Has-Selector $opts) { Resolve-Window $opts } else { $null }
472 930 Invoke-RacingGuard $opts
931 + if ($target -ne $null -and $focus -ne 'skip') { Set-Foreground $target $focus }
473 932 [Windows.Forms.SendKeys]::SendWait($keySpec)
474 - return [pscustomobject] [ordered] @{ ok = $true; keys = $keySpec }
933 + return [pscustomobject] [ordered] @{ ok = $true; keys = $keySpec; focus = $focus; foreground = (Get-ForegroundInfo) }
477 936 $action = (Str-Opt $opts 'Action').ToLowerInvariant()