我试图单击画图的保存按钮,但它无法识别窗口控件。难道我做错了什么?例如,此代码仅识别窗口的标题,但不识别该窗口的控件。
有人可以帮忙吗?
Add-Type -AssemblyName System.Drawing
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName UIAutomationClient
Add-Type -AssemblyName UIAutomationTypes
Add-Type -AssemblyName System.Xml.Linq
$nameProcess = "mspaint"
$windowTitle = "Untitled"
$processes = [System.Diagnostics.Process]::GetProcessesByName($nameProcess)
foreach ($process in $processes) {
if ($process.MainWindowTitle.Contains($windowTitle)) {
if ($process -ne $null) {
$root = [System.Windows.Automation.AutomationElement]::FromHandle($process.MainWindowHandle)
$elements = $root.FindAll([System.Windows.Automation.TreeScope]::Subtree, [System.Windows.Automation.Condition]::TrueCondition) | Select-Object -Unique
foreach ($item in $elements) {
if ($item -ne $null) {
$pattern = $null
if ($item.TryGetCurrentPattern([System.Windows.Automation.InvokePattern]::Pattern, [ref]$pattern)) {
write-host $item.Current.Name -ForegroundColor Green
if ($item.Current.Name -eq "Save") {
$pattern.Invoke()
}
}
}
}
}
}
}
最佳答案
正如我所评论的,Windows 10 及更高版本的 MSPaint 可能不支持旧的 UIA2 界面,而需要 UIA3。
我已经能够使用FlaUI按下“保存”按钮遵循 this answer 第一部分中的步骤后,库(UIA2 和 UIA3 的 .NET 包装器)从 NuGet 下载其二进制文件。
Add-Type -Path $PSScriptRoot\assemblies\bin\Release\net48\publish\FlaUI.UIA3.dll
# Create UIA3 interface
$automation = [FlaUI.UIA3.UIA3Automation]::new()
# For each mspaint process
foreach( $process in Get-Process mspaint ) {
# Attach FlaUI to the process
$app = [FlaUI.Core.Application]::Attach( $process )
# For each top level window of mspaint
foreach( $wnd in $app.GetAllTopLevelWindows( $automation ) ) {
# Filter all descendants - get button named 'Save'
$wnd.FindAllDescendants() |
Where-Object { $_.ControlType -eq 'Button' -and $_.Name -eq 'Save' } |
ForEach-Object {
# Click the button using the "Invoke" pattern
$_.Patterns.Invoke.Pattern.Invoke()
}
}
}
关于powershell - 如何使用 UIAutomation 单击 Paint 的保存按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75484324/