Skip to content

Instantly share code, notes, and snippets.

@zett42
Last active June 19, 2023 16:08
Show Gist options
  • Save zett42/b5407343d04d571f802a1ca76496d61d to your computer and use it in GitHub Desktop.
Save zett42/b5407343d04d571f802a1ca76496d61d to your computer and use it in GitHub Desktop.
Listen to WindowOpenedEvent using UI automation in PowerShell with inline C#
# 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