With PowerShell, how to switch minimized application to normal state?

Viewed 496

Given a single-instance desktop application ccTest.exe, how can I use PowerShell (v6 or 7) to run the application in the Normal state if it is already running in Minimized state.

I need access to controls in the main window so it must be in Normal state. Get-Process works to check if the app is running. If not, then launch it with Start-Process and -WindowStyle Normal parameter. But Start-Process does not work if the the single-instance app is already running Minimized.

Due to timing constraints I'd rather not close ccTest.exe if minimized and then launch with Start-Process. Here is the test code.

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
}

So how to change State/Style from Minimized to Normal to run the needed function?

1 Answers

This should do the trick.

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
}

References:

Maximize window and bring it in front with powershell

Get window state of another process

Related