20 20 $ErrorActionPreference = 'Stop'
21 -Add-Type -AssemblyName System.Drawing,System.Windows.Forms
21 +$script:win32DriveStart = [Diagnostics.Stopwatch]::StartNew()
23 +# Assemblies are loaded on demand: list/focus/window/uia never pay for WinForms.
24 +function Import-Drawing {
25 + if (-not $script:win32DriveDrawing) { Add-Type -AssemblyName System.Drawing; $script:win32DriveDrawing = $true }
28 +function Import-Forms {
29 + if (-not $script:win32DriveForms) { Import-Drawing; Add-Type -AssemblyName System.Windows.Forms; $script:win32DriveForms = $true }
32 +$script:win32DriveNativeSource = @"
25 35 using System.Runtime.InteropServices;
52 62 [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 63 [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);
54 64 [DllImport("kernel32.dll")] public static extern uint GetTickCount();
55 - [DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
56 65 [DllImport("user32.dll")] public static extern bool IsIconic(IntPtr hWnd);
66 + [DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
57 67 [DllImport("user32.dll", SetLastError=true)] public static extern bool SetProcessDpiAwarenessContext(IntPtr value);
58 68 [DllImport("shcore.dll")] public static extern int SetProcessDpiAwareness(int value);
59 69 [DllImport("user32.dll")] public static extern bool SetProcessDPIAware();
172 +# Compiling this P/Invoke surface costs about a second and spawns csc.exe, which
173 +# flashes a console window. Cache the assembly per source hash and reuse it.
174 +function Import-Native([string] $Source) {
175 + if ('Win32DriveNative' -as [type]) { return 'loaded' }
176 + $sha = [Security.Cryptography.SHA256]::Create()
178 + $hash = ([BitConverter]::ToString($sha.ComputeHash([Text.Encoding]::UTF8.GetBytes($Source))) -replace '-', '').Substring(0, 16)
179 + } finally { $sha.Dispose() }
180 + $dir = Join-Path $env:LOCALAPPDATA 'win32-drive'
181 + $dll = Join-Path $dir "Win32DriveNative-$hash.dll"
182 + if (Test-Path $dll) {
184 + Add-Type -Path $dll
188 + if (-not (Test-Path $dir)) { New-Item -ItemType Directory -Force -Path $dir | Out-Null }
189 + $staging = Join-Path $dir ('build-' + [guid]::NewGuid().ToString('N') + '.dll')
190 + Add-Type -TypeDefinition $Source -OutputAssembly $staging -OutputType Library
191 + try { Move-Item -LiteralPath $staging -Destination $dll -Force } catch { Remove-Item -LiteralPath $staging -Force -ErrorAction SilentlyContinue }
192 + if (Test-Path $dll) { Add-Type -Path $dll } else { Add-Type -TypeDefinition $Source }
196 +$script:win32DriveNativeLoad = Import-Native $script:win32DriveNativeSource
162 198 function Set-DpiAwareness {
163 199 try { if ([Win32DriveNative]::SetProcessDpiAwarenessContext([IntPtr] (-4))) { return 'per-monitor-v2' } } catch {}
164 200 try { if ([Win32DriveNative]::SetProcessDpiAwareness(2) -eq 0) { return 'per-monitor' } } catch {}
172 208 $Value | ConvertTo-Json -Depth 24 -Compress
211 +# Errors carry a stable code, a hint, and whatever context saves the agent a
212 +# follow-up query (candidate windows, foreground state, idle time).
213 +function Fail([string] $Code, [string] $Message, [string] $Hint, $Extra) {
214 + $payload = [ordered] @{ ok = $false; error = $Message; code = $Code }
215 + if ($Hint) { $payload['hint'] = $Hint }
216 + if ($Extra) { foreach ($key in $Extra.Keys) { $payload[$key] = $Extra[$key] } }
217 + $script:win32DriveFailure = $payload
221 +function Get-FailurePayload([string] $Name, $ErrorRecord) {
222 + $message = $ErrorRecord.Exception.Message
223 + $payload = if ($script:win32DriveFailure -and $script:win32DriveFailure['error'] -eq $message) {
224 + $script:win32DriveFailure
226 + [ordered] @{ ok = $false; error = $message; code = 'unexpected' }
228 + $script:win32DriveFailure = $null
229 + $payload['cmd'] = $Name
230 + [pscustomobject] $payload
233 +$script:win32DriveValueOptions = @('Hwnd','Process','TitleContains','X','Y','Width','Height','Out','Text','Keys','Action','Button','Count','DurationMs','IdleMs','TimeoutMs','CountdownMs','Set','Depth','Mode','Scope','Focus','Cursor','Return','Refresh','Method','Name','AutomationId','ClassName','ControlType','Index','Value','Json','File')
234 +$script:win32DriveFlagOptions = @('Pointer','ContinueOnError','NoCountdown')
175 236 function Parse-Options([string[]] $ArgList) {
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')
180 239 for ($i = 0; $i -lt $ArgList.Count; $i++) {
181 240 $arg = $ArgList[$i]
182 241 if ($arg.StartsWith('-')) {
183 242 $key = $arg.TrimStart('-')
184 - if ($flagOptions -contains $key) { $opts[$key] = $true; continue }
185 - if ($valueOptions -notcontains $key) { throw "Unknown option: -$key" }
186 - if ($i + 1 -ge $ArgList.Count) { throw "Missing value for -$key" }
243 + if ($script:win32DriveFlagOptions -contains $key) { $opts[$key] = $true; continue }
244 + if ($script:win32DriveValueOptions -notcontains $key) {
245 + Fail 'unknown-option' "Unknown option: -$key" 'run help for the option catalog' @{ knownOptions = @($script:win32DriveValueOptions + $script:win32DriveFlagOptions) }
247 + if ($i + 1 -ge $ArgList.Count) { Fail 'missing-value' "Missing value for -$key" "pass a value after -$key" }
188 249 $opts[$key] = $ArgList[$i]
193 - if ($pos.Count -gt 0) { throw ('Unexpected positional args: ' + ($pos -join ' ')) }
254 + if ($pos.Count -gt 0) { Fail 'positional-args' ('Unexpected positional args: ' + ($pos -join ' ')) 'every input is a named option, for example -Text hello' }
209 270 [string] $Opts[$Name]
273 +function Get-ProcessNames {
274 + if ($null -ne $script:win32DriveProcessNames) { return $script:win32DriveProcessNames }
276 + foreach ($proc in (Get-Process -ErrorAction SilentlyContinue)) { $map[[int64] $proc.Id] = $proc.ProcessName }
277 + $script:win32DriveProcessNames = $map
212 281 function Get-Windows {
213 282 $script:win32DriveWindows = @()
283 + $script:win32DriveForeground = [Win32DriveNative]::GetForegroundWindow()
284 + $names = Get-ProcessNames
214 285 [Win32DriveNative]::EnumWindows({ param($h, $l)
215 286 if ([Win32DriveNative]::IsWindowVisible($h)) {
216 287 $sb = [Text.StringBuilder]::new(1024)
219 290 if ($title.Trim().Length -gt 0) {
220 291 [uint32] $procId = 0
221 292 [void] [Win32DriveNative]::GetWindowThreadProcessId($h, [ref] $procId)
222 - $proc = Get-Process -Id $procId -ErrorAction SilentlyContinue
223 293 $rect = Get-Rect $h
224 294 $script:win32DriveWindows += [pscustomobject] [ordered] @{
225 295 hwnd = $h.ToInt64()
226 296 pid = [int64] $procId
227 - process = if ($proc) { $proc.ProcessName } else { $null }
297 + process = $names[[int64] $procId]
231 301 width = $rect.Right - $rect.Left
232 302 height = $rect.Bottom - $rect.Top
303 + z = $script:win32DriveWindows.Count
304 + minimized = [bool] [Win32DriveNative]::IsIconic($h)
305 + focused = $h -eq $script:win32DriveForeground
259 332 function Get-FocusMode($Opts) {
260 333 $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' }
334 + if (@('auto','require','skip') -notcontains $focus) { Fail 'invalid-value' 'Focus must be auto, require, or skip' 'require uses activation APIs only, auto adds a caption click, skip does not focus' }
335 + if ($focus -eq 'auto' -and -not $Opts.ContainsKey('Pointer')) {
336 + Fail 'pointer-consent' 'Focus auto falls back to clicking the target caption' 'ask the user first, then pass -Pointer'
273 348 $title = $sb.ToString()
274 349 [void] [Win32DriveNative]::GetWindowThreadProcessId($h, [ref] $procId)
276 - $proc = Get-Process -Id $procId -ErrorAction SilentlyContinue
351 + $proc = (Get-ProcessNames)[[int64] $procId]
278 353 try { $hung = [bool] [Win32DriveNative]::IsHungAppWindow($h) } catch {}
279 354 [pscustomobject] [ordered] @{
280 355 hwnd = $h.ToInt64()
281 356 pid = [int64] $procId
282 - process = if ($proc) { $proc.ProcessName } else { $null }
313 388 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') }
389 + if ([Win32DriveNative]::IsIconic($Hwnd)) {
390 + Fail 'window-minimized' 'Target window is minimized' ('restore it first: window -Hwnd ' + $Hwnd.ToInt64() + ' -Action restore') @{ hwnd = $Hwnd.ToInt64() }
315 392 $deadline = (Get-Date).AddMilliseconds($TimeoutMs)
317 394 # Windows denies activation to background processes while the user is
325 402 if ($Mode -eq 'auto' -and (Invoke-CaptionClick $Hwnd)) { return }
326 403 $fg = Get-ForegroundInfo
327 404 $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))
405 + $hint = if ($fg.hung) {
406 + 'nothing can be driven until that window recovers'
407 + } elseif ($Mode -eq 'require') {
408 + 'ask the user, then retry with -Focus auto -Pointer, which clicks the target caption'
410 + 'retry when the user is idle, or drive the app with uia-invoke/uia-set instead'
412 + Fail 'focus-denied' ('Could not focus target window ' + $Hwnd.ToInt64() + ': ' + $reason) $hint @{
413 + hwnd = $Hwnd.ToInt64()
415 + lockTimeoutMs = [int64] [Win32DriveNative]::GetForegroundLockTimeout()
416 + idleMs = Get-IdleMs
421 +function Select-Windows($Opts) {
422 + $wins = @(Get-Windows)
423 + $proc = Str-Opt $Opts 'Process'
424 + $title = Str-Opt $Opts 'TitleContains'
425 + if ($Opts.ContainsKey('Hwnd')) {
426 + $wanted = Long-Opt $Opts 'Hwnd'
427 + $wins = @($wins | Where-Object { $_.hwnd -eq $wanted })
429 + if ($proc) { $wins = @($wins | Where-Object { $_.process -eq $proc }) }
430 + if ($title) { $wins = @($wins | Where-Object { $_.title.IndexOf($title, [StringComparison]::OrdinalIgnoreCase) -ge 0 }) }
434 +function Get-WindowInfo([IntPtr] $Hwnd) {
435 + @(Get-Windows) | Where-Object { $_.hwnd -eq $Hwnd.ToInt64() } | Select-Object -First 1
332 438 function Resolve-Window($Opts) {
333 439 if ($Opts.ContainsKey('Hwnd')) {
334 440 $hwnd = [IntPtr] (Long-Opt $Opts 'Hwnd')
335 - if (-not [Win32DriveNative]::IsWindow($hwnd)) { throw 'Invalid window handle' }
441 + if (-not [Win32DriveNative]::IsWindow($hwnd)) {
442 + Fail 'stale-window' 'Invalid window handle' 'the window closed or the handle is wrong: run list again' @{ hwnd = $hwnd.ToInt64() }
338 - $wins = @(Get-Windows)
339 - $proc = Str-Opt $Opts 'Process'
340 - $title = Str-Opt $Opts 'TitleContains'
341 - if ($proc) { $wins = @($wins | Where-Object { $_.process -eq $proc }) }
342 - if ($title) { $wins = @($wins | Where-Object { $_.title.IndexOf($title, [StringComparison]::OrdinalIgnoreCase) -ge 0 }) }
343 - if ($wins.Count -eq 0) { throw 'No matching window' }
344 - if ($wins.Count -gt 1) { throw ('Ambiguous window: ' + (($wins | Select-Object -First 8 hwnd,process,title) | ConvertTo-Json -Compress)) }
446 + $wins = @(Select-Windows $Opts)
447 + if ($wins.Count -eq 0) {
448 + $proc = Str-Opt $Opts 'Process'
449 + $candidates = if ($proc) {
450 + @(Get-Windows | Where-Object { $_.process -like "*$proc*" } | Select-Object -First 8)
452 + @(Get-Windows | Select-Object -First 8)
454 + Fail 'no-window' 'No matching window' 'relax the selector; candidates lists what is open right now' @{ candidates = $candidates }
456 + if ($wins.Count -gt 1) {
457 + Fail 'ambiguous-window' ('Ambiguous window: ' + $wins.Count + ' matches') 'pick one -Hwnd from candidates' @{ candidates = @($wins | Select-Object -First 8) }
345 459 [IntPtr] $wins[0].hwnd
355 469 function Wait-UserIdle([int] $IdleMs, [int] $TimeoutMs) {
356 470 $start = Get-Date
357 471 while ((Get-IdleMs) -lt $IdleMs) {
358 - if (((Get-Date) - $start).TotalMilliseconds -gt $TimeoutMs) { throw "User not idle for $IdleMs ms" }
472 + if (((Get-Date) - $start).TotalMilliseconds -gt $TimeoutMs) {
473 + Fail 'user-active' "User not idle for $IdleMs ms" 'the human is using the machine: retry later, raise -TimeoutMs, or use a background command' @{ idleMs = Get-IdleMs; requiredIdleMs = $IdleMs }
359 475 Start-Sleep -Milliseconds 100
363 -function Draw-Indicator($X = $null, $Y = $null, [int] $DurationMs = 180) {
479 +# One overlay renderer: quick flash for background commands, banner plus
480 +# countdown for foreground takeovers, which the human can veto by touching
481 +# keyboard or mouse.
482 +function Show-Overlay($X = $null, $Y = $null, [string] $Banner = $null, [int] $DurationMs = 180, [bool] $AbortOnInput = $false) {
484 + $state = [pscustomobject] @{ Banner = $Banner; Remaining = $DurationMs }
485 + $bannerScreen = if ($null -ne $X -and $null -ne $Y) {
486 + [Windows.Forms.Screen]::FromPoint([Drawing.Point]::new([int] $X, [int] $Y))
488 + [Windows.Forms.Screen]::PrimaryScreen
365 491 foreach ($screen in [Windows.Forms.Screen]::AllScreens) {
366 492 $b = $screen.Bounds
495 + $showBanner = $Banner -and $screen.DeviceName -eq $bannerScreen.DeviceName
369 496 $form = New-Object Windows.Forms.Form
370 497 $form.FormBorderStyle = 'None'
371 498 $form.StartPosition = 'Manual'
386 513 $localY = [int]$targetY - $b.Top
387 514 $event.Graphics.DrawEllipse($pen, $localX - 24, $localY - 24, 48, 48)
517 + $text = $state.Banner
518 + if ($state.Remaining -gt 0) {
519 + $text = $text + "`nacting in " + [Math]::Max(0, [Math]::Round($state.Remaining / 1000.0, 1)) + 's - touch keyboard or mouse to cancel'
521 + $font = New-Object Drawing.Font 'Segoe UI', 20, ([Drawing.FontStyle]::Bold)
522 + $back = New-Object Drawing.SolidBrush ([Drawing.Color]::FromArgb(235, 20, 0, 0))
523 + $fore = New-Object Drawing.SolidBrush ([Drawing.Color]::White)
525 + $size = $event.Graphics.MeasureString($text, $font)
526 + $boxWidth = $size.Width + 48
527 + $boxHeight = $size.Height + 28
528 + $boxX = ($sender.Width - $boxWidth) / 2
530 + $event.Graphics.FillRectangle($back, $boxX, $boxY, $boxWidth, $boxHeight)
531 + $event.Graphics.DrawRectangle($pen, $boxX, $boxY, $boxWidth, $boxHeight)
532 + $event.Graphics.DrawString($text, $font, $fore, $boxX + 24, $boxY + 14)
534 + $font.Dispose(); $back.Dispose(); $fore.Dispose()
401 549 [Windows.Forms.Application]::DoEvents()
402 550 Start-Sleep -Milliseconds 20
404 - if ($DurationMs -gt 0) { Start-Sleep -Milliseconds $DurationMs }
553 + if ($DurationMs -gt 0) {
554 + $deadline = (Get-Date).AddMilliseconds($DurationMs)
556 + $remaining = ($deadline - (Get-Date)).TotalMilliseconds
557 + if ($remaining -le 0) { break }
558 + $state.Remaining = [int] $remaining
559 + if ($Banner) { foreach ($form in $forms) { $form.Invalidate() } }
560 + [Windows.Forms.Application]::DoEvents()
561 + Start-Sleep -Milliseconds 50
562 + if ($AbortOnInput -and (Get-IdleMs) -lt 150) { $completed = $false; break }
405 565 foreach ($opacity in 0.7,0.45,0.2,0.0) {
406 566 foreach ($form in $forms) { $form.Opacity = $opacity }
407 567 [Windows.Forms.Application]::DoEvents()
410 570 foreach ($form in $forms) { $form.Close(); $form.Dispose() }
411 571 [Windows.Forms.Application]::DoEvents()
575 +function Draw-Indicator($X = $null, $Y = $null, [int] $DurationMs = 180) {
576 + [void] (Show-Overlay $X $Y $null $DurationMs $false)
579 +# Background commands: wait for an input gap, flash once, act.
414 580 function Invoke-RacingGuard($Opts, $X = $null, $Y = $null) {
415 581 $idle = Int-Opt $Opts 'IdleMs' 800
416 582 $timeout = Int-Opt $Opts 'TimeoutMs' 10000
418 584 Draw-Indicator $X $Y 120
587 +# Foreground/pointer commands: same wait, then a named banner with a countdown
588 +# the human can veto.
589 +function Invoke-Takeover($Opts, [string] $Label, $X = $null, $Y = $null) {
590 + $idle = Int-Opt $Opts 'IdleMs' 800
591 + $timeout = Int-Opt $Opts 'TimeoutMs' 10000
592 + Wait-UserIdle $idle $timeout
593 + $countdown = if ($Opts.ContainsKey('NoCountdown')) { 0 } else { Int-Opt $Opts 'CountdownMs' 1200 }
594 + if (-not (Show-Overlay $X $Y $Label $countdown $true)) {
595 + Fail 'takeover-aborted' 'Foreground takeover cancelled by user input' 'the human took the machine back mid-countdown: ask before retrying' @{ label = $Label }
421 599 function Theme-Name($Value) {
422 600 if ([int]$Value -eq 0) { 'dark' } else { 'light' }
484 662 function Get-PixelColor([int] $X, [int] $Y) {
485 664 $bmp = [Drawing.Bitmap]::new(1, 1)
486 665 $g = [Drawing.Graphics]::FromImage($bmp)
496 675 function Capture-Region([int] $X, [int] $Y, [int] $Width, [int] $Height, [string] $Out) {
497 677 $bmp = [Drawing.Bitmap]::new($Width, $Height)
498 678 $g = [Drawing.Graphics]::FromImage($bmp)
521 701 function Capture-Window([IntPtr] $Hwnd, [string] $Out) {
522 703 $frame = Get-Rect $Hwnd
523 704 $raw = Get-RawRect $Hwnd
524 705 $w = $frame.Right - $frame.Left
639 820 $root = if (Has-Selector $Opts) {
640 821 [Windows.Automation.AutomationElement]::FromHandle((Resolve-Window $Opts))
642 - throw 'element commands need a window selector: -Hwnd, -Process, or -TitleContains'
823 + Fail 'missing-selector' 'element commands need a window selector' 'pass -Hwnd, -Process, or -TitleContains; list shows all windows'
644 825 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'
826 + Fail 'missing-filter' 'element commands need -Name, -AutomationId, -ClassName, or -ControlType' 'read the tree with uia first, then address the element; filters accept wildcards'
647 828 # ControlType narrows the tree walk; the string filters are wildcards, because
648 829 # bridged providers generate volatile class names and automation ids.
658 839 $property = $filter[1]
659 840 $found = @($found | Where-Object { [string] $_.Current.$property -like $pattern })
661 - if ($found.Count -eq 0) { throw 'No matching element' }
842 + if ($found.Count -eq 0) {
843 + $sample = @($root.FindAll([Windows.Automation.TreeScope]::Children, [Windows.Automation.Condition]::TrueCondition) | Select-Object -First 8 | ForEach-Object { Describe-UiaElement $_ })
844 + Fail 'no-element' 'No matching element' 'filters are wildcards against the uia tree; candidates lists the direct children' @{ candidates = $sample }
662 846 if ($Opts.ContainsKey('Index')) {
663 847 $index = Int-Opt $Opts 'Index'
664 - if ($index -lt 0 -or $index -ge $found.Count) { throw ('Index out of range: ' + $found.Count + ' matching elements') }
848 + if ($index -lt 0 -or $index -ge $found.Count) {
849 + Fail 'index-out-of-range' ('Index out of range: ' + $found.Count + ' matching elements') 'use an index between 0 and matches-1' @{ matches = $found.Count }
665 851 return $found[$index]
667 853 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))
854 + Fail 'ambiguous-element' ('Ambiguous element: ' + $found.Count + ' matches') 'narrow the filters or pass -Index' @{ candidates = @($found | Select-Object -First 8 | ForEach-Object { Describe-UiaElement $_ }) }
692 877 return 'BM_CLICK'
695 - throw 'Element supports no invokable pattern; use click -Pointer instead'
880 + Fail 'no-pattern' 'Element supports no invokable pattern' 'this app exposes no usable accessibility action: ask the user, then use click -Pointer' @{ element = (Describe-UiaElement $Element) }
698 883 function Set-UiaElementValue($Element, [string] $Value) {
705 890 $native = Get-UiaNativeHandle $Element
706 891 if ($native -ne [IntPtr]::Zero -and (Send-WindowText $native $Value)) { return 'WM_CHAR' }
707 - throw 'Element exposes no value pattern; use type -Pointer instead'
892 + Fail 'no-pattern' 'Element exposes no settable value' 'ask the user, then focus it and use type -Pointer' @{ element = (Describe-UiaElement $Element) }
710 895 # Posted characters reach a native edit control without focus and still raise
968 +function Get-ReturnMode($Opts) {
969 + $mode = (Str-Opt $Opts 'Return' 'restore').ToLowerInvariant()
970 + if (@('restore','keep') -notcontains $mode) { Fail 'invalid-value' 'Return must be restore or keep' 'restore puts the human back in their window when the action is done' }
974 +function Format-TakeoverLabel([string] $Action, $Target, $X = $null, $Y = $null) {
975 + $where = if ($Target) {
976 + $title = [string] $Target.title
977 + if ($title.Length -gt 60) { $title = $title.Substring(0, 57) + '...' }
978 + $Target.process + ': ' + $title
979 + } elseif ($null -ne $X) {
982 + 'the focused window'
984 + 'win32-drive ' + $Action + ' -> ' + $where
987 +function Restore-Foreground($Previous, [string] $Mode) {
988 + if ($Mode -ne 'restore' -or $null -eq $Previous -or $Previous.hwnd -eq 0) { return $null }
989 + $handle = [IntPtr] $Previous.hwnd
990 + if ([Win32DriveNative]::GetForegroundWindow() -eq $handle) { return $Previous.hwnd }
991 + if (-not [Win32DriveNative]::IsWindow($handle)) { return $null }
992 + if ([Win32DriveNative]::Foreground($handle, 400) -or [Win32DriveNative]::ForegroundUnlocked($handle, 400)) { return $Previous.hwnd }
996 +# One process start costs more than every action in it, so a whole interaction
997 +# can be sent as an ordered step list with pauses between steps.
998 +function Invoke-Batch($Opts) {
999 + $json = if ($Opts.ContainsKey('Json')) { Str-Opt $Opts 'Json' }
1000 + elseif ($Opts.ContainsKey('File')) { Get-Content -Raw -LiteralPath (Str-Opt $Opts 'File') }
1001 + else { [Console]::In.ReadToEnd() }
1002 + if (-not $json -or $json.Trim().Length -eq 0) {
1003 + Fail 'batch-empty' 'batch needs steps' 'pass -Json, -File, or pipe JSON on stdin: [{"cmd":"list"},{"cmd":"wait","ms":300}]'
1005 + # Assigning first matters: @(ConvertFrom-Json ...) wraps the whole array in one element.
1007 + $parsed = ConvertFrom-Json $json
1009 + Fail 'batch-invalid-json' ('Batch steps are not valid JSON: ' + $_.Exception.Message) 'shells mangle embedded quotes: prefer -File steps.json or pipe the JSON on stdin' @{ received = $json.Substring(0, [Math]::Min(200, $json.Length)) }
1011 + $steps = @($parsed)
1012 + $continueOnError = $Opts.ContainsKey('ContinueOnError')
1015 + for ($index = 0; $index -lt $steps.Count; $index++) {
1016 + $step = $steps[$index]
1017 + $name = [string] $step.cmd
1019 + foreach ($property in $step.PSObject.Properties) {
1020 + if ($property.Name -in @('cmd','ms')) { continue }
1021 + if ($property.Value -is [bool]) {
1022 + if ($property.Value) { $stepOpts[$property.Name] = $true }
1025 + if ($script:win32DriveValueOptions -notcontains $property.Name -and $script:win32DriveFlagOptions -notcontains $property.Name) {
1026 + Fail 'unknown-option' ("Unknown option in step " + $index + ": " + $property.Name) 'steps use the same option names as the command line'
1028 + $stepOpts[$property.Name] = [string] $property.Value
1030 + $stepWatch = [Diagnostics.Stopwatch]::StartNew()
1032 + $payload = if ($name -eq 'wait') {
1033 + $ms = if ($null -ne $step.ms) { [int] $step.ms } else { 250 }
1034 + Start-Sleep -Milliseconds $ms
1035 + [pscustomobject] [ordered] @{ ok = $true; waitedMs = $ms }
1037 + Invoke-DriveCommand $name $stepOpts
1039 + $results += (Add-Envelope $name $payload $index $stepWatch)
1041 + $results += (Add-Envelope $name (Get-FailurePayload $name $_) $index $stepWatch)
1042 + $failedAt = $index
1043 + if (-not $continueOnError) { break }
1046 + [pscustomobject] [ordered] @{
1047 + ok = ($null -eq $failedAt)
1048 + steps = $steps.Count
1049 + ran = $results.Count
1050 + failedAt = $failedAt
1051 + results = $results
1055 +function Add-Envelope([string] $Name, $Payload, $Step = $null, $Watch = $null) {
1056 + $elapsed = if ($Watch) { [int] $Watch.ElapsedMilliseconds } else { [int] $script:win32DriveStart.ElapsedMilliseconds }
1057 + $result = $Payload | Add-Member -PassThru -NotePropertyName cmd -NotePropertyValue $Name -Force
1058 + $result = $result | Add-Member -PassThru -NotePropertyName elapsedMs -NotePropertyValue $elapsed -Force
1059 + if ($null -ne $Step) { $result = $result | Add-Member -PassThru -NotePropertyName step -NotePropertyValue $Step -Force }
783 1063 function Show-Help {
784 1064 [pscustomobject] [ordered] @{
786 1066 runtime = 'Windows PowerShell 5.1+'
787 1067 dpiAwareness = $script:win32DriveDpi
1068 + nativeLoad = $script:win32DriveNativeLoad
1069 + speed = 'process start dominates: send one batch of steps instead of many invocations; every result carries cmd and elapsedMs'
1070 + errors = 'failures are JSON with code, hint, and context: candidates for no-window/ambiguous-window/no-element, foreground plus lockTimeoutMs plus idleMs for focus-denied'
1071 + takeover = 'pointer and focus commands show a named banner with a countdown; user input during the countdown aborts with code takeover-aborted'
788 1072 coordinates = 'screen pixels; with a window selector, click -X/-Y are relative to the DWM frame bounds reported by list and shot'
789 1073 racingGuard = 'racing commands fade a 16px red border/ring, wait for user idle, then act'
790 1074 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'
792 1076 globalOptions = '-IdleMs n (default 800) and -TimeoutMs n (default 10000) tune the racing guard'
793 1077 commands = [ordered] @{
794 1078 help = [ordered] @{ racing = $false; usage = 'help' }
795 - list = [ordered] @{ racing = $false; usage = 'list' }
1079 + batch = [ordered] @{ racing = $null; usage = 'batch -File steps.json | batch (JSON on stdin) | batch -Json ''[{"cmd":"list"},{"cmd":"wait","ms":300}]'' [-ContinueOnError]' }
1080 + list = [ordered] @{ racing = $false; usage = 'list [-Hwnd n|-Process p|-TitleContains t]' }
796 1081 shot = [ordered] @{ racing = $false; usage = 'shot [-Hwnd n|-Process p -TitleContains t|-X x -Y y -Width w -Height h] [-Out file.png]' }
797 1082 pixel = [ordered] @{ racing = $false; usage = 'pixel -X x -Y y' }
798 1083 uia = [ordered] @{ racing = $false; usage = 'uia [-Hwnd n|-Process p|-TitleContains t] [-Depth n]' }
803 1088 idle = [ordered] @{ racing = $false; usage = 'idle' }
804 1089 clipboard = [ordered] @{ racing = $null; usage = 'clipboard | clipboard -Set text' }
805 1090 theme = [ordered] @{ racing = $true; usage = 'theme | theme -Mode dark|light [-Scope apps|system|both] [-Refresh broadcast|full]' }
806 - overlay = [ordered] @{ racing = $false; usage = 'overlay [-X x -Y y] [-DurationMs ms]' }
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]' }
1091 + overlay = [ordered] @{ racing = $false; usage = 'overlay [-X x -Y y] [-Text banner] [-DurationMs ms]' }
1092 + click = [ordered] @{ racing = $true; takeover = $true; usage = 'click -Pointer [-Hwnd n|-Process p|-TitleContains t] [-X x -Y y] [-Button left|right] [-Count n] [-Focus auto|require|skip] [-Cursor restore|keep] [-Return restore|keep] [-CountdownMs n|-NoCountdown]' }
1093 + type = [ordered] @{ racing = $true; takeover = $true; usage = 'type [-Hwnd n|-Process p|-TitleContains t] -Text text [-Focus auto|require|skip] [-Pointer] [-Method unicode|sendkeys] [-Return restore|keep] [-CountdownMs n|-NoCountdown]' }
1094 + key = [ordered] @{ racing = $true; takeover = $true; usage = 'key [-Hwnd n|-Process p|-TitleContains t] -Keys "^s" [-Focus auto|require|skip] [-Pointer] [-Return restore|keep] [-CountdownMs n|-NoCountdown]' }
810 1095 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]' }
815 -function Invoke-CommandImpl {
816 - $opts = Parse-Options $Rest
817 - switch ($Command.ToLowerInvariant()) {
1100 +function Invoke-DriveCommand([string] $Name, $Opts) {
1102 + switch ($Name.ToLowerInvariant()) {
818 1103 'help' { return Show-Help }
819 - 'list' { return [pscustomobject] [ordered] @{ ok = $true; windows = @(Get-Windows) } }
1105 + $windows = if (Has-Selector $opts) { @(Select-Windows $opts) } else { @(Get-Windows) }
1106 + return [pscustomobject] [ordered] @{
1108 + count = $windows.Count
1109 + foreground = (Get-ForegroundInfo)
1110 + idleMs = Get-IdleMs
1111 + windows = $windows
820 1114 'idle' { return [pscustomobject] [ordered] @{ ok = $true; idleMs = Get-IdleMs } }
821 1115 'focus' { return (Get-ForegroundInfo) | Add-Member -PassThru -NotePropertyName ok -NotePropertyValue $true }
825 1119 return [pscustomobject] [ordered] @{ ok = $true; x = $p.X; y = $p.Y }
828 - Draw-Indicator (Int-Opt $opts 'X') (Int-Opt $opts 'Y') (Int-Opt $opts 'DurationMs' 650)
829 - return [pscustomobject] [ordered] @{ ok = $true }
1122 + $banner = Str-Opt $opts 'Text'
1123 + $duration = Int-Opt $opts 'DurationMs' 650
1124 + $completed = Show-Overlay (Int-Opt $opts 'X') (Int-Opt $opts 'Y') $banner $duration ($opts.ContainsKey('Pointer') -eq $false -and $null -ne $banner)
1125 + return [pscustomobject] [ordered] @{ ok = $true; banner = $banner; durationMs = $duration; completed = $completed }
832 1128 $x = Int-Opt $opts 'X'
838 1134 $out = Str-Opt $opts 'Out'
839 1135 if (Has-Selector $opts) { return Capture-Window (Resolve-Window $opts) $out }
840 1137 $screen = [System.Windows.Forms.SystemInformation]::VirtualScreen
841 1138 $x = Int-Opt $opts 'X' $screen.Left
842 1139 $y = Int-Opt $opts 'Y' $screen.Top
870 1167 return [pscustomobject] [ordered] @{ ok = $true; tree = Dump-Uia $el 0 $depth }
873 1171 if ($opts.ContainsKey('Set')) {
874 1172 Invoke-RacingGuard $opts
875 1173 [Windows.Forms.Clipboard]::SetText((Str-Opt $opts 'Set'))
883 1181 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' }
1184 + if (-not $opts.ContainsKey('Pointer')) {
1185 + Fail 'pointer-consent' 'click injects pointer input' 'ask the user first, then pass -Pointer; uia-invoke acts without pointer or focus'
887 1187 $button = (Str-Opt $opts 'Button' 'left').ToLowerInvariant()
888 1188 $count = Int-Opt $opts 'Count' 1
889 1189 $focus = Get-FocusMode $opts
1190 + $returnMode = Get-ReturnMode $opts
890 1191 $cursorMode = (Str-Opt $opts 'Cursor' 'restore').ToLowerInvariant()
891 - if (@('restore','keep') -notcontains $cursorMode) { throw 'Cursor must be restore or keep' }
1192 + if (@('restore','keep') -notcontains $cursorMode) { Fail 'invalid-value' 'Cursor must be restore or keep' 'restore puts the pointer back where the human left it' }
892 1193 $x = Int-Opt $opts 'X'
893 1194 $y = Int-Opt $opts 'Y'
895 1197 if (Has-Selector $opts) {
896 1198 $hwnd = Resolve-Window $opts
1199 + $target = Get-WindowInfo $hwnd
897 1200 $r = Get-Rect $hwnd
898 1201 if ($x -eq $null) { $x = [int] (($r.Left + $r.Right) / 2) } else { $x = $r.Left + $x }
899 1202 if ($y -eq $null) { $y = [int] (($r.Top + $r.Bottom) / 2) } else { $y = $r.Top + $y }
901 - if ($x -eq $null -or $y -eq $null) { throw 'click needs -X and -Y unless targeting a window center' }
1204 + if ($x -eq $null -or $y -eq $null) { Fail 'missing-option' 'click needs -X and -Y unless targeting a window center' 'pass screen coordinates, or a window selector for a center click' }
902 1205 $origin = New-Object Win32DriveNative+POINT
903 1206 [void] [Win32DriveNative]::GetCursorPos([ref] $origin)
1207 + $previous = Get-ForegroundInfo
904 1208 # Focus after the guard: activation is only granted during input gaps.
905 - Invoke-RacingGuard $opts $x $y
1209 + Invoke-Takeover $opts (Format-TakeoverLabel "$button click" $target $x $y) $x $y
906 1210 if ($hwnd -ne $null -and $focus -ne 'skip') { Set-Foreground $hwnd $focus }
907 1211 Invoke-PointerClick $x $y $button $count $false
908 1212 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) }
1213 + $returnedTo = Restore-Foreground $previous $returnMode
1214 + return [pscustomobject] [ordered] @{
1221 + cursor = $cursorMode
1222 + return = $returnMode
1223 + returnedTo = $returnedTo
1225 + foreground = (Get-ForegroundInfo)
912 1229 $text = Str-Opt $opts 'Text'
913 - if ($null -eq $text) { throw 'type needs -Text' }
1230 + if ($null -eq $text) { Fail 'missing-option' 'type needs -Text' 'pass the literal text; newlines become Enter' }
914 1231 $focus = Get-FocusMode $opts
915 - $target = if (Has-Selector $opts) { Resolve-Window $opts } else { $null }
1232 + $returnMode = Get-ReturnMode $opts
1233 + $handle = if (Has-Selector $opts) { Resolve-Window $opts } else { $null }
1234 + $target = if ($handle) { Get-WindowInfo $handle } else { $null }
916 1235 $defaultMethod = if ([IntPtr]::Size -eq 8) { 'unicode' } else { 'sendkeys' }
917 1236 $method = (Str-Opt $opts 'Method' $defaultMethod).ToLowerInvariant()
918 - if (@('unicode','sendkeys') -notcontains $method) { throw 'Method must be unicode or sendkeys' }
919 - Invoke-RacingGuard $opts
920 - if ($target -ne $null -and $focus -ne 'skip') { Set-Foreground $target $focus }
1237 + if (@('unicode','sendkeys') -notcontains $method) { Fail 'invalid-value' 'Method must be unicode or sendkeys' 'unicode sends the text verbatim; sendkeys uses the legacy escaped syntax' }
1238 + $previous = Get-ForegroundInfo
1239 + Invoke-Takeover $opts (Format-TakeoverLabel 'type' $target)
1240 + if ($handle -ne $null -and $focus -ne 'skip') { Set-Foreground $handle $focus }
921 1241 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) }
1242 + else { Import-Forms; [Windows.Forms.SendKeys]::SendWait((Escape-SendKeysText $text)) }
1243 + $returnedTo = Restore-Foreground $previous $returnMode
1244 + return [pscustomobject] [ordered] @{
1246 + chars = $text.Length
1249 + return = $returnMode
1250 + returnedTo = $returnedTo
1252 + foreground = (Get-ForegroundInfo)
926 1256 $keySpec = Str-Opt $opts 'Keys'
927 - if (-not $keySpec) { throw 'key needs -Keys' }
1257 + if (-not $keySpec) { Fail 'missing-option' 'key needs -Keys' 'SendKeys syntax, for example ^s or %{F4}' }
928 1258 $focus = Get-FocusMode $opts
929 - $target = if (Has-Selector $opts) { Resolve-Window $opts } else { $null }
930 - Invoke-RacingGuard $opts
931 - if ($target -ne $null -and $focus -ne 'skip') { Set-Foreground $target $focus }
1259 + $returnMode = Get-ReturnMode $opts
1260 + $handle = if (Has-Selector $opts) { Resolve-Window $opts } else { $null }
1261 + $target = if ($handle) { Get-WindowInfo $handle } else { $null }
1262 + $previous = Get-ForegroundInfo
1263 + Invoke-Takeover $opts (Format-TakeoverLabel "key $keySpec" $target)
1264 + if ($handle -ne $null -and $focus -ne 'skip') { Set-Foreground $handle $focus }
932 1266 [Windows.Forms.SendKeys]::SendWait($keySpec)
933 - return [pscustomobject] [ordered] @{ ok = $true; keys = $keySpec; focus = $focus; foreground = (Get-ForegroundInfo) }
1267 + $returnedTo = Restore-Foreground $previous $returnMode
1268 + return [pscustomobject] [ordered] @{
1272 + return = $returnMode
1273 + returnedTo = $returnedTo
1275 + foreground = (Get-ForegroundInfo)
936 1279 $action = (Str-Opt $opts 'Action').ToLowerInvariant()
937 - if (-not $action) { throw 'window needs -Action' }
1280 + if (-not $action) { Fail 'missing-option' 'window needs -Action' 'move, min, max, restore, or close' }
938 1281 $hwnd = Resolve-Window $opts
939 1282 Invoke-RacingGuard $opts
940 1283 switch ($action) {
950 1293 'max' { [void] [Win32DriveNative]::ShowWindow($hwnd, 3) }
951 1294 'restore' { [void] [Win32DriveNative]::ShowWindow($hwnd, 9) }
952 1295 'close' { [void] [Win32DriveNative]::PostMessage($hwnd, 0x0010, [IntPtr]::Zero, [IntPtr]::Zero) }
953 - default { throw "Unknown window action: $action" }
1296 + default { Fail 'invalid-value' "Unknown window action: $action" 'move, min, max, restore, or close' }
1298 + Start-Sleep -Milliseconds 120
1299 + return [pscustomobject] [ordered] @{
1301 + hwnd = $hwnd.ToInt64()
1303 + window = (Get-WindowInfo $hwnd)
1304 + foreground = (Get-ForegroundInfo)
955 - return [pscustomobject] [ordered] @{ ok = $true; hwnd = $hwnd.ToInt64(); action = $action }
957 - default { throw "Unknown command: $Command" }
1308 + Fail 'unknown-command' "Unknown command: $Name" 'run help for the command catalog' @{ commands = @((Show-Help).commands.Keys) }
962 - Write-Json (Invoke-CommandImpl)
1314 + $options = Parse-Options $Rest
1315 + $payload = if ($Command.ToLowerInvariant() -eq 'batch') { Invoke-Batch $options } else { Invoke-DriveCommand $Command $options }
1316 + Write-Json (Add-Envelope $Command $payload)
965 - Write-Json ([pscustomobject] [ordered] @{ ok = $false; error = $_.Exception.Message; command = $Command })
1319 + Write-Json (Add-Envelope $Command (Get-FailurePayload $Command $_))