代码之家  ›  专栏  ›  技术社区  ›  Ben Laan

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

  •  11
  • Ben Laan  · 技术社区  · 16 年前

    我要改造一个老人 cmd PowerShell命令,当前使用:

    START "My Title" Path/To/ConsoleApp.exe
    

    这可以像预期的那样用我的标题作为窗口标题来启动consoleapp。这已被正确工作的启动过程所取代,但不提供更改标题的机制。

    有别的办法吗 没有 使用 CMD 命令?

    4 回复  |  直到 9 年前
        1
  •  10
  •   George Howarth    16 年前

    更改进程主窗口的文本时有一个小问题:如果在启动进程后尝试直接更改文本,则可能会由于许多可能的原因之一(例如,函数调用时显示文本的控件的句柄不存在)而失败。所以解决方法是使用 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")
    

    请注意,在您进行了自己的更改之后,应用程序本身仍然可以更改窗口文本。

        2
  •  5
  •   stej    16 年前

    我用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')
    
        3
  •  1
  •   Shay Levy    16 年前

    $host.ui.rawui.windowtitle=“新标题”

    正如George已经说过的,任何人/任何人都可以将其设置回原处(例如自定义提示函数)。

        4
  •  0
  •   Lou O.    9 年前

    如果要使用具有自定义标题的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)
    

    注意那些脱离标题字符串的严肃字符,它们是至关重要的!

    推荐文章