在 PowerShell 中将控制台设置为最顶层

2024-02-16

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

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


这需要一些 .NET 互操作,如本博客中所述:

TechEd 2012 中的脚本…第 1 部分(将 PowerShell 窗口保持在顶部) https://blogs.msdn.microsoft.com/taylorb/2012/06/12/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)

Edit:

如评论中所述:如果您来自批处理文件,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)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 PowerShell 中将控制台设置为最顶层 的相关文章

随机推荐