Techibee.com

Get active window on desktop using PowerShell

In today’s post, I want to show how to know what is the active window on Desktop.  I came across this requirement when I want to determine, what is the application user is currently using. There is no PowerShell CMDLET that can do this straight away, so we need to rely on a bit of C# coding to achieve this.

The user32.dll DLL provides function called GetForegroundWindow which provides the window handle of active application/process. We can find the process name by Get-Process with returned window handle.

Code:

[CmdletBinding()]            
Param(            
)            
Add-Type @"
  using System;
  using System.Runtime.InteropServices;
  public class UserWindows {
    [DllImport("user32.dll")]
    public static extern IntPtr GetForegroundWindow();
}
"@            
try {            
$ActiveHandle = [Windows]::GetForegroundWindow()            
$Process = Get-Process | ? {$_.MainWindowHandle -eq $activeHandle}            
$Process | Select ProcessName, @{Name="AppTitle";Expression= {($_.MainWindowTitle)}}            
} catch {            
 Write-Error "Failed to get active Window details. More Info: $_"            
}

Output:

You can download this script from Technet Gallery as well.

Exit mobile version