【问题标题】:With PowerShell, how to switch minimized application to normal state?使用 PowerShell,如何将最小化的应用程序切换到正常状态?
【发布时间】:2022-01-09 17:54:26
【问题描述】:

给定一个单实例桌面应用程序 ccTest.exe,如果它已经在最小化状态下运行,我如何使用 PowerShell(v6 或 7)在正常状态下运行该应用程序。

我需要访问主窗口中的控件,因此它必须处于正常状态。 Get-Process 用于检查应用程序是否正在运行。如果没有,则使用 Start-Process 和 -WindowStyle Normal 参数启动它。但是如果单实例应用程序已经在运行 Minimized,则 Start-Process 不起作用。

由于时间限制,如果最小化,我宁愿不关闭 ccTest.exe,然后使用 Start-Process 启动。这是测试代码。

if (Get-Process | Select MainWindowTitle, ProcessName, Id | where {$_.MainWindowTitle -like "ccTest*"})
{ 
    if Minimized make it Normal
    execute needed function
}
else
{
   start-process "C:\Program Files (x86)\Test\ccTest.exe" -WindowStyle Normal
   execute needed function
}

那么如何将 State/Style 从 Minimized 更改为 Normal 以运行所需的功能?

【问题讨论】:

    标签: windows powershell start-process


    【解决方案1】:

    这应该可以解决问题。

    Add-Type -AssemblyName UIAutomationClient
    
    $MyProcess = Get-Process | where { $_.MainWindowTitle -like "ccTest*" }
    if ($null -ne $MyProcess) { 
        # if Minimized make it Normal
        $ae = [System.Windows.Automation.AutomationElement]::FromHandle($MyProcess.MainWindowHandle)
        $wp = $ae.GetCurrentPattern([System.Windows.Automation.WindowPatternIdentifiers]::Pattern)
        if ($wp.Current.WindowVisualState -eq 'Minimized') {
            $wp.SetWindowVisualState('Normal') 
        }
        # execute needed function
    }
    else {
        start-process "C:\Program Files (x86)\Test\ccTest.exe" -WindowStyle Normal
        # execute needed function
    }
    

    参考资料:

    Maximize window and bring it in front with powershell

    Get window state of another process

    【讨论】:

    • 感谢两位的回答。 Sage 几乎完成了这项工作,但在 If (... -eq 'Minimized') 语句中,True 被返回给 PowerShell。这一定是把焦点转移到了 PowerShell,所以我的函数现在可以正常工作了。所以我添加了 mklement0 的代码,一切正常。
    • 不太熟悉 Stackoverflow 的工作原理。有没有办法奖励你们俩?
    • @mklement0 好点。我相应地更新了我的答案。至于您的第二条评论,要在不更改状态的情况下激活,这似乎可以正常工作 $wp.SetWindowVisualState($wp.Current.WindowVisualState) 。不确定是否有办法在更改状态时不关注焦点。使用 PInvoke / findWindow,您可以轻松确定之前具有焦点的窗口并立即将焦点返回给它,但也许有一种更清洁的方法。
    • 感谢更新,@SagePourpre - 以及$wp.SetWindowVisualState($wp.Current.WindowVisualState) 的好点子。至于不激活:如果您使用SW_SHOWNOACTIVATE(或SW_SHOWMINNOACTIVESW_SHOWNA),您原来的ShowWindowAsync P/Invoke 方法肯定会起作用,但我对纯UIAutomation 解决方案很好奇,但找不到任何解决方案。
    猜你喜欢
    • 2016-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    • 1970-01-01
    • 2017-09-02
    相关资源
    最近更新 更多