Last active
June 19, 2023 16:08
-
-
Save zett42/b5407343d04d571f802a1ca76496d61d to your computer and use it in GitHub Desktop.
Listen to WindowOpenedEvent using UI automation in PowerShell with inline C#
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Windows PowerShell (5.1) script | |
# Watch top-level window creation and log window name, process ID and process name. | |
Add-Type -ReferencedAssemblies UIAutomationClient, UIAutomationTypes -TypeDef @' | |
using System; | |
using System.Windows.Automation; | |
public class WindowWatcher | |
{ | |
public static void Watch() | |
{ | |
Automation.AddAutomationEventHandler( | |
WindowPattern.WindowOpenedEvent, | |
AutomationElement.RootElement, | |
TreeScope.Children, | |
(sender, e) => { | |
var element = sender as AutomationElement; | |
var process = System.Diagnostics.Process.GetProcessById( element.Current.ProcessId ); | |
Console.WriteLine(String.Format("Window Title: {0}, ProcessId: {1}, ProcessName: {2}", element.Current.Name, element.Current.ProcessId, process.ProcessName )); | |
}); | |
Console.ReadLine(); | |
Automation.RemoveAllEventHandlers(); | |
} | |
} | |
'@ | |
[WindowWatcher]::Watch() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment