Skip to content

Commit ab2a217

Browse files
fix(app usages): retrieve process ID of the active window on Windows
1 parent 7bdbacd commit ab2a217

File tree

1 file changed

+11
-4
lines changed

1 file changed

+11
-4
lines changed

windows/getActiveWindow.ps1

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,20 +11,27 @@ public class WindowHelper
1111
1212
[DllImport("user32.dll")]
1313
public static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);
14+
15+
[DllImport("user32.dll")]
16+
public static extern int GetWindowThreadProcessId(IntPtr hWnd, out int lpdwProcessId);
1417
}
1518
"@
1619

1720
# Get the handle of the active window
18-
$hwnd = [WindowHelper]::GetForegroundWindow()
21+
$foregroundWindow = [WindowHelper]::GetForegroundWindow()
1922

2023
# Create a StringBuilder to hold the window title
2124
$titleBuilder = New-Object System.Text.StringBuilder 256
22-
[WindowHelper]::GetWindowText($hwnd, $titleBuilder, $titleBuilder.Capacity) | Out-Null
25+
[WindowHelper]::GetWindowText($foregroundWindow, $titleBuilder, $titleBuilder.Capacity) | Out-Null
2326
$title = $titleBuilder.ToString()
2427

28+
# Get the process ID of the active window
29+
$processId = 0
30+
[WindowHelper]::GetWindowThreadProcessId($foregroundWindow, [ref] $processId)
31+
2532
# Get the process associated with the active window
26-
$process = Get-Process | Where-Object { $_.MainWindowHandle -eq $hwnd }
27-
$processName = if ($process) { $process.Name } else { "Unknown" }
33+
$process = Get-Process -Id $processId -ErrorAction SilentlyContinue
34+
$processName = if ($process) { $process.Name } else { "" }
2835

2936
# Output the results
3037
Write-Output "$title,$processName"

0 commit comments

Comments
 (0)