Peter Hinchley

Learning in Public

✪ Changing Window Titles using PowerShell

Toward the end of my previous post on using SetWindowsHookEx to create global system hooks, I alluded to my failed attempt at changing window titles with PowerShell by hooking WM_SETTEXT messages. There is, however, another way to achieve this goal, albeit, far less elegant.

Instead of proactively intercepting the messages used to set window titles, we can retrospectively modify the existing titles of all windows on a timed schedule.

The following PowerShell code uses a system timer, which fires every second, to call the Win32 function SetWindowsText. The function adds the text "Top Secret" to the start of every window title that does not already include the prefix.

# Prefix to add to window titles.
$prefix = "Top Secret"

# How often to update window titles (in milliseconds).
$interval = 1000

Add-Type -TypeDefinition @"
using System;
using System.Runtime.InteropServices;

public static class Win32 {
  [DllImport("User32.dll", EntryPoint="SetWindowText")]
  public static extern int SetWindowText(IntPtr hWnd, string strTitle);

$timer = New-Object System.Timers.Timer

$timer.Enabled = $true
$timer.Interval = $interval
$timer.AutoReset = $true

function Change-Window-Titles($prefix) {
  Get-Process | ? {$_.mainWindowTitle -and $_.mainWindowTitle -notlike "$($prefix)*"} | %{
    [Win32]::SetWindowText($_.mainWindowHandle, "$prefix - $($_.mainWindowTitle)")

Register-ObjectEvent -InputObject $timer -EventName Elapsed -Action {
  Change-Window-Titles $prefix

To test the program, save the code to C:\Temp\ChangeWindowTitles.ps1, open a command prompt, change into C:\Temp, and run:

powershell.exe -noexit -file ChangeWindowTitles.ps1

The noexit argument is necessary to ensure the program stays active.

Run the code, open some windows, and after a short delay, watch the "Top Secret" prefix magically appear on all windows with visible titles.

Note: Due to the way I have chosen to enumerate application windows, this code will not correctly adjust the titles of MDI (multiple document interface) applications - like Microsoft Word.