powershell 如何使用UI自动化点击Paint的保存按钮?

xmd2e60i  于 2023-03-08  发布在  Shell
关注(0)|答案(1)|浏览(254)

我试图点击画图的保存按钮,但是它不能识别窗口控件。我做错了什么吗?例如,这段代码只能识别窗口的标题,但是不能识别该窗口的控件。
有人能帮忙吗?

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()
                        }
                    }
                }
            }
        }
    }
}
kgsdhlau

kgsdhlau1#

正如我所评论的,Windows 10和更新版本的MSPaint可能不支持旧的UIA2接口,而是需要UIA3。
在按照this answer第一部分的步骤从NuGet下载它的二进制文件之后,我已经能够使用FlaUI库(UIA2和UIA3的.NET Package 器)按下“保存”按钮。

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() 
            }  
    }   
}

相关问题