How to prevent the console title from being changed by another application

Viewed 86

I have a simple PowerShell script which uses the $host.ui.rawui.windowtitle option to set the window title. My script then executes an interactive, character based application (let's call it myapp.exe). However, as long as myapp.exe is running, the window title is changed to the title of the myapp application. As soon as I exit myapp.exe, the title I originally set is shown again. Is there any way to prevent the title from being changed by myapp.exe? Thank you very much for any help in advance!

Kind regards, Eric

1 Answers

I don't think you can prevent other apps from changing the console window title. You may start a thread job using Start-ThreadJob that periodically resets the window title to your desired value if it has changed.

# Start a thread job to periodically reset the console window title
$null = Start-ThreadJob { param( $rawUI, $windowTitle )
    while( $true ) {
        # If the window title has changed, reset it
        if( $rawUI.WindowTitle -ne $windowTitle ) {
            $rawUI.WindowTitle = $windowTitle
        }
        # A delay is important so the CPU is not hogged
        Start-Sleep -Millis 250
    }
} -ArgumentList $host.ui.RawUI, 'My window title'

# For testing: Simulate another process that sets the window title:
$host.UI.RawUI.WindowTitle = 'foo bar'

You can see that "foo bar" briefly appears in the window title, but will be reset to our desired window title shortly after.

Start-ThreadJob requires PS 5.1 or newer. I've tried a solution for older PowerShell versions using Start-Job, but that doesn't work, propably because normal jobs run in a separate process, having no access to the PowerShell console that launched them.

Start-ThreadJob otoh runs in a thread in the same process, so it does have access to the console.

Related