简体   繁体   English

如何防止控制台标题被另一个应用程序更改

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

I have a simple PowerShell script which uses the $host.ui.rawui.windowtitle option to set the window title.我有一个简单的 PowerShell 脚本,它使用$host.ui.rawui.windowtitle选项来设置窗口标题。 My script then executes an interactive, character based application (let's call it myapp.exe).然后我的脚本会执行一个交互式的、基于字符的应用程序(我们称之为 myapp.exe)。 However, as long as myapp.exe is running, the window title is changed to the title of the myapp application.但是,只要 myapp.exe 正在运行,窗口标题就会更改为 myapp 应用程序的标题。 As soon as I exit myapp.exe, the title I originally set is shown again.退出 myapp.exe 后,我最初设置的标题再次显示。 Is there any way to prevent the title from being changed by myapp.exe?有什么方法可以防止 myapp.exe 更改标题? Thank you very much for any help in advance!非常感谢您提前提供的任何帮助!

Kind regards, Eric亲切的问候,埃里克

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-ThreadJob启动线程作业,如果窗口标题已更改,它会定期将窗口标题重置为您想要的值。

# 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.您可以看到“foo bar”短暂地出现在窗口标题中,但很快就会重置为我们想要的窗口标题。

Start-ThreadJob requires PS 5.1 or newer. Start-ThreadJob需要 PS 5.1 或更高版本。 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-Job为旧 PowerShell 版本提供解决方案,但这不起作用,可能是因为正常作业在单独的进程中运行,无法访问启动它们的 PowerShell 控制台。

Start-ThreadJob otoh runs in a thread in the same process, so it does have access to the console. Start-ThreadJob otoh 在同一进程中的线程中运行,因此它确实可以访问控制台。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM