I've looked hard for any examples about .Net events revealing a change of the MainWindowTitle of a process (or a corresponding property).
For detecting changes to file content I can simply use
function Register-FileWatcherEvent {
param (
[string]$folder,
[string]$file,
[string]$SourceIdentifier = 'File_Changed'
)
$watcher = New-Object IO.FileSystemWatcher $folder, $file -Property @{
IncludeSubdirectories = $false
EnableRaisingEvents = $true
}
$watcher.NotifyFilter = 'LastWrite'
Register-ObjectEvent $watcher -EventName 'Changed' -SourceIdentifier $SourceIdentifier
}
But what object, properties and notifier should I use for registering an event for change of MainWindowTitle or a corresponding property?
Take 2
I tried messing around with WinEventHooks (and I have no idea what I'm doing here ;)
Some event do get registered but it triggers on mouse over instead of title change...
Add-Type -TypeDefinition @"
using System;
using System.Runtime.InteropServices;
public static class User32 {
public delegate void WinEventDelegate(
IntPtr hWinEventHook,
uint eventType,
IntPtr hwnd,
int idObject,
int idChild,
uint dwEventThread,
uint dwmsEventTime);
[DllImport("user32.dll")]
public static extern IntPtr SetWinEventHook(
uint eventMin,
uint eventMax,
IntPtr hmodWinEventProc,
WinEventDelegate lpfnWinEventProc,
uint idProcess,
uint idThread, uint dwFlags);
[DllImport("user32.dll")]
public static extern bool UnhookWinEvent(IntPtr hWinEventHook);
}
"@
$processId = (Get-Process -Name notepad).Id
$WinEventDelegate = [User32+WinEventDelegate]{
param (
$hWinEventHook,
$eventType,
$hwnd,
$idObject,
$idChild,
$dwEventThread,
$dwmsEventTime
)
if ($eventType -eq 0x800C) {
$windowTitle = Get-Process -Id $processId |
Select-Object -ExpandProperty MainWindowTitle
Write-Host "Window title changed to: $windowTitle"
}
}
$hWinEventHook = [User32]::SetWinEventHook(
0x800C,
0x800C,
[IntPtr]::Zero,
$WinEventDelegate,
$processId,
0,
0
)
$handler = {
param (
$sender,
$eventArgs
)
$windowTitle = Get-Process -Id $processId |
Select-Object -ExpandProperty MainWindowTitle
Write-Host "Window title changed to: $windowTitle"
}
Register-ObjectEvent -InputObject $null `
-EventName EventRecord `
-Action $handler `
-SourceIdentifier "WindowTitleChanged" `
-SupportEvent
# To unregister the event, use the following command:
# Unregister-Event -SourceIdentifier "WindowTitleChanged"
0x800C is EVENT_OBJECT_NAMECHANGE, but can be different kind of objects.
MS Learn - Event Constants (Winuser.h)
So I reckon I need to check what was changed at each event trigger?