如何启动基于控制台的过程并使用PowerShell应用自定义标题
-
01-10-2019 - |
题
我正在转换一个旧 cmd
命令到PowerShell,目前使用:
START "My Title" Path/To/ConsoleApp.exe
这是按预期启动Consoleapp的窗口标题的工作。这已被启动过程所取代,该过程正常工作,但没有提供更改标题的机制。
还有另一种方法可以做到这一点吗 没有 诉诸于使用 cmd
命令?
解决方案
在更改过程的主窗口的文本时,有一个小怪癖:如果您在启动该过程后尝试直接更改文本,则可能由于许多可能的原因之一(例如,显示显示的句柄)函数调用时不存在文本)。因此,解决方案是使用 WaitForInputIdle()
尝试更改文本之前:
Add-Type -TypeDefinition @"
using System;
using System.Runtime.InteropServices;
public static class Win32Api
{
[DllImport("User32.dll", EntryPoint = "SetWindowText")]
public static extern int SetWindowText(IntPtr hWnd, string text);
}
"@
$process = Start-Process -FilePath "notepad.exe" -PassThru
$process.WaitForInputIdle()
[Win32Api]::SetWindowText($process.MainWindowHandle, "My Custom Text")
请注意,在您进行更改后,应用程序本身仍然可以更改窗口文本。
其他提示
我尝试了cmd.exe,它运行良好。
Add-Type -Type @"
using System;
using System.Runtime.InteropServices;
namespace WT {
public class Temp {
[DllImport("user32.dll")]
public static extern bool SetWindowText(IntPtr hWnd, string lpString);
}
}
"@
$cmd = Start-Process cmd -PassThru
[wt.temp]::SetWindowText($cmd.MainWindowHandle, 'some text')
$ host.ui.rawui.windowtitle =“新标题”
正如乔治已经说过的那样,任何人/任何人都可以将其放回原处(例如自定义提示功能)。
如果您想与PowerShell一起使用自定义标题来产生一个过程:
$StartInfo = new-object System.Diagnostics.ProcessStartInfo
$StartInfo.FileName = "$pshome\powershell.exe"
$StartInfo.Arguments = "-NoExit -Command `$Host.UI.RawUI.WindowTitle=`'Your Title Here`'"
[System.Diagnostics.Process]::Start($StartInfo)
请注意,逃脱标题的字符串的坟墓角色至关重要!
不隶属于 StackOverflow