How to Bring Program to the Front with Powershell

The aim of this page📝 is to illustrate bringing a program’s window to the front with a simple command from Powershell. Here is a particular code from my $profile, mainly for jumping into the VLC player, where I listen to BBC essential mix for routine tasks and don’t want to use WIN+<number> as that’s already reserved for other tasks and I don’t want to restart instances if I am listening to 2-hour mix that which I am pausing and unpausing, etc.

Pavol Kutaj
2 min readOct 12, 2023
jumping to CamelPhat Essential Mix 2023 ;)
  • In PowerShell, you can get a list of running processes using the Get-Process cmdlet.
  • Once you have access to a process, you can read its properties or call its methods to perform various actions.
  • However, some actions require interacting with the Windows API, which is not directly accessible from PowerShell.
  • For example, bringing a running program’s window to the front requires calling the SetForegroundWindow function from the user32.dll library.
  • To call this function from PowerShell, you need to use the Add-Type cmdlet to define a new class with a static extern method for SetForegroundWindow.
  • Then, you can call this method with the handle of the program’s main window as an argument.
  • The handle of the main window can be obtained from the MainWindowHandle property of the process.

CODE

function goto ($process_name) {
Add-Type @"
using System;
using System.Runtime.InteropServices;
public class Program {
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetForegroundWindow(IntPtr hWnd);
}
"@

$processes = Get-Process -Name "*${process_name}*"
$process = $processes | Where-Object { $_.MainWindowHandle -ne 0 } | Select-Object -First 1
if ($process) {
$hwnd = $process.MainWindowHandle
[Program]::SetForegroundWindow($hwnd)
} else {
Write-Host "Program is not running or does not have a MainWindowHandle."
}}

--

--

Responses (2)