powershell - 如何使用 UIAutomation 单击 Paint 的保存按钮?

标签 powershell winapi ui-automation

我试图单击画图的保存按钮,但它无法识别窗口控件。难道我做错了什么?例如,此代码仅识别窗口的标题,但不识别该窗口的控件。

有人可以帮忙吗?

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/

相关文章:

powershell - 我将如何重新编写此硬币翻转循环

PowerShell 复制到 $null

c# - Win32Api USB SetupDiGetDeviceInterfaceDetail 失败

c - 从技术角度来看,MinGW 做了什么使 gcc 在 Windows 上成为可能?

c# - 通过 UI 自动化清除 RichTextBox 文本?

ios - 在移动设备(iPad 设置屏幕)上滑动时,始终在右半部分滑动。如何在左半部分执行滑动

vba - Powershell脚本将Microsoft Access查询或表导出到CSV文件

Azure 自动缩放规则映射不正确

c++ - boost::interprocess_mutex 与 Win32 native 互斥锁的性能如何?

android - 空测试套件。 Espresso