虽然有很多关于如何将表单置于最上方的建议,但我没找到任何可以使我的控制台置于最上方的内容。
所以我的问题是:在脚本执行期间,如何使我的控制台置于最前?
虽然有很多关于如何将表单置于最上方的建议,但我没找到任何可以使我的控制台置于最上方的内容。
所以我的问题是:在脚本执行期间,如何使我的控制台置于最前?
$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)
编辑:
如评论中所述:如果您来自批处理文件,则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)
$type::SetWindowPos($handle, -1, 0, 0, 0, 0, 0x0003)
替换$type::SetWindowPos($handle, $alwaysOnTop, 0, 0, 0, 0, 0x0003)
。 - mklement0[DllImport("kernel32.dll")] public static extern IntPtr GetConsoleWindow();
添加到$signature
的值中,将$handle = ...
这一行替换为$handle = $type::GetConsoleWindow()
。 - mklement0