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.
Great code, just one problem:
public class UserWindows
Then here:
$ActiveHandle = [Windows]::GetForegroundWindow()
Change to:
$ActiveHandle = [UserWindows]::GetForegroundWindow()
And then it works like a charm 🙂
Nice code, but quite useless.
If you start the script, then the focus is not longer on the original window.
Run it with a keyboard shortcut.
You need to run as a scheduled job under current logged on user.
Thanks for the script. And especially Carsten! You made my day!
Thanks