【问题标题】:Set console Top-Most in PowerShell在 PowerShell 中将控制台设置为 Top-Most
【发布时间】:2019-10-24 13:15:51
【问题描述】:

因此,虽然有很多关于如何将 forms 设置在最顶层的建议,但我找不到任何可以让我的控制台运行在最顶层的东西。

所以我的问题是:如何让我的控制台在脚本期间运行在最顶层?

【问题讨论】:

标签: powershell console topmost


【解决方案1】:

这需要一些 .NET 互操作,详见本博客:

Scripts From TechEd 2012… Part 1 (Keeping PowerShell Window On Top)

我已经复制了下面的相关代码,以防链接的网站消失:

$signature = @'
[DllImport("user32.dll")]
public static extern bool SetWindowPos(
    IntPtr hWnd,
    IntPtr hWndInsertAfter,
    int X,
    int Y,
    int cx,
    int cy,
    uint uFlags);
'@

$type = Add-Type -MemberDefinition $signature -Name SetWindowPosition -Namespace SetWindowPos -Using System.Text -PassThru

$handle = (Get-Process -id $Global:PID).MainWindowHandle
$alwaysOnTop = New-Object -TypeName System.IntPtr -ArgumentList (-1)
$type::SetWindowPos($handle, $alwaysOnTop, 0, 0, 0, 0, 0x0003)

编辑:

如 cmets 中所述:如果您来自批处理文件,PowerShell 在子进程中运行并且不拥有控制台窗口,因此您必须进行更改:

$signature = @'
[DllImport("kernel32.dll")] public static extern IntPtr GetConsoleWindow();
[DllImport("user32.dll")]
public static extern bool SetWindowPos(
    IntPtr hWnd,
    IntPtr hWndInsertAfter,
    int X,
    int Y,
    int cx,
    int cy,
    uint uFlags);
'@

$type = Add-Type -MemberDefinition $signature -Name SetWindowPosition -Namespace SetWindowPos -Using System.Text -PassThru

$handle = $type::GetConsoleWindow()
$type::SetWindowPos($handle, -1, 0, 0, 0, 0, 0x0003)

【讨论】:

  • @Omglolyes:您可以将$type::SetWindowPos($handle, $alwaysOnTop, 0, 0, 0, 0, 0x0003) 替换为$type::SetWindowPos($handle, -1, 0, 0, 0, 0, 0x0003)
  • @boxdog,您的脚本在 Powershell 中有 curly quotesaren't well supported
  • @Omglolyes:如果您来自批处理文件,PowerShell 在子进程中运行并且不拥有控制台窗口,因此您必须进行更改:将 [DllImport("kernel32.dll")] public static extern IntPtr GetConsoleWindow(); 添加到$signature 的值,将 $handle = ... 行替换为 $handle = $type::GetConsoleWindow()
  • @RichMoss:最好避免使用非 ASCII 范围的引号,但请注意 PowerShell 本身 完全支持它们。问题通常是 字符编码 之一 - 请参阅 this answer
  • @RichMoss。正如我在帖子中所说,我从博客中复制/粘贴了它,所以这就是奇怪的引用的来源。话虽如此,我应该检查一下,而不是仅仅假设它没问题。现已修复。
猜你喜欢
  • 1970-01-01
  • 2012-10-11
  • 1970-01-01
  • 2020-06-25
  • 1970-01-01
  • 1970-01-01
  • 2015-07-16
  • 1970-01-01
  • 2011-09-30
相关资源
最近更新 更多