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.
Comments on this entry are closed.
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
Thanks! This is still works in Windows 11, over seven years after the original post. I needed to make the public class change Jon mentioned. I added a loop, that appends to an array, and exports to a csv resulting in a nice little activity log with no overhead.
(definitely not useless…)
For some reason explorer.exe doesn’t register and returns a null value.