开发者

Maximize window and bring it in front with powershell

开发者 https://www.devze.com 2023-02-11 12:03 出处:网络
Is there a way to bring a window in fron开发者_运维问答t from powershell? I tried this to hide all windows (working) and bring me the powershell back (not working)

Is there a way to bring a window in fron开发者_运维问答t from powershell? I tried this to hide all windows (working) and bring me the powershell back (not working)

[void] [System.Reflection.Assembly]::LoadWithPartialName("'Microsoft.VisualBasic")
$shell = New-Object -ComObject "Shell.Application"
$shell.MinimizeAll()

$a = Get-Process | Where-Object {$_.Name -like "powershell"}
[Microsoft.VisualBasic.Interaction]::AppActivate($a.ID)

Any suggestions?


The PowerShell Community Extensions has a cmdlet to assist with this. You use it like so:

Set-ForegroundWindow (Get-Process PowerShell).MainWindowHandle

or

Set-ForegroundWindow (Get-Process -id $pid).MainWindowHandle

To activate/show a window try this (assuming you're on PowerShell 2.0):

$sig = '[DllImport("user32.dll")] public static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);'
Add-Type -MemberDefinition $sig -name NativeMethods -namespace Win32
Stop-Process -Name Notepad -ea 0;Notepad.exe
$hwnd = @(Get-Process Notepad)[0].MainWindowHandle
# Minimize window
[Win32.NativeMethods]::ShowWindowAsync($hwnd, 2)
# Restore window
[Win32.NativeMethods]::ShowWindowAsync($hwnd, 4)
Stop-Process -Name Notepad


This is cheating a bit since it's using WScript, but the following one-liner places the window in the foreground without requiring any external cmdlet installation.

In the example below, "notepad" is the process name associated with the window.

Credit goes to the Idera forum posting here by JSanders:

(New-Object -ComObject WScript.Shell).AppActivate((get-process notepad).MainWindowTitle)


Wscript one liner is working for me when I replace .MainWindowTitle to .Description at the end. So the line becomes:

(New-Object -ComObject WScript.Shell).AppActivate((get-process notepad).Description)

Yet to find a similar one liner for maximizing it...

0

精彩评论

暂无评论...
验证码 换一张
取 消