Skip to content

Instantly share code, notes, and snippets.

@lansalot
Created January 24, 2019 23:26
Show Gist options
  • Save lansalot/b7c9c1f0e881ad01fca55660d05bee32 to your computer and use it in GitHub Desktop.
Save lansalot/b7c9c1f0e881ad01fca55660d05bee32 to your computer and use it in GitHub Desktop.
Find the active window process owner
Add-Type @"
using System;
using System.Runtime.InteropServices;
public static class Win32Api
{
[System.Runtime.InteropServices.DllImportAttribute( "User32.dll", EntryPoint = "GetWindowThreadProcessId" )]
public static extern int GetWindowThreadProcessId ( [System.Runtime.InteropServices.InAttribute()] System.IntPtr hWnd, out int lpdwProcessId );
[System.Runtime.InteropServices.DllImportAttribute( "User32.dll", EntryPoint = "GetForegroundWindow" )]
public static extern IntPtr GetForegroundWindow();
}
"@
while ($true) {
$HWND = [Win32Api]::GetForegroundWindow()
$FGWindowPid = [IntPtr]::Zero
[Win32Api]::GetWindowThreadProcessId( $HWND, [ref] $FGWindowPid );
Write-Output "HWND: $($HWND) HWND Owner Process: $($FGWindowPid )"
#if process in foreground is notepad
if($FGWindowPid -eq (Get-Process Notepad).id) {
"true"
} else {
"false"
}
sleep 3
}
@lansalot
Copy link
Author

Someone asked how to do this on Reddit - print $true if the active window was Notepad. Quick learning exercise for me..

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment