如何启动基于控制台的流程并使用Powershell应用自定义标题

Ben*_*aan 11 powershell start-process

我正在将旧cmd命令转换为Powershell,目前使用:

START "My Title" Path/To/ConsoleApp.exe
Run Code Online (Sandbox Code Playgroud)

这可以按预期使用My Title作为窗口标题启动ConsoleApp.这已被替换为正常工作的Start-Process,但未提供更改标题的机制.

有没有其他方法可以做到这一点,而无需使用cmd命令?

Geo*_*rth 10

There is a small quirk when changing the text of the process' main window: if you try to change the text straight after you have started the process, it may fail due to one of many possible reasons (e.g. the handle to the control which displays the text does not exist at the time of the function call). So the solution is to use the WaitForInputIdle() method before trying to change the text:

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")
Run Code Online (Sandbox Code Playgroud)

Be aware that the application itself can still change the window text after you have made your own change.

  • 这对我来说不起作用,至少不能用于`CMD.EXE`作为有问题的过程(由OP指定).`WaitForInputIdle()`为非GUI应用程序引发`InvalidOperationException`,为非GUI应用程序引发`MainWindowHandle`为'0`. (2认同)

ste*_*tej 5

我用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')
Run Code Online (Sandbox Code Playgroud)

  • 这个解决方案并不总能为我工作.我在尝试设置窗口标题之前添加了延迟(Start-Sleep -s 5),现在看起来效果更好. (2认同)