You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在PowerShell中获取/设置当前窗口的屏幕位置?

PowerShell窗口位置设置/移动最简实现方法

问题背景

需要让PowerShell脚本所在的窗口每次打开都固定到指定的屏幕坐标位置(Windows默认会随机调整窗口打开位置),但尝试使用[console]::SetWindowPosition()时出现错误——该方法实际是调整控制台缓冲区内的窗口视图位置,而非窗口在屏幕上的实际位置。

错误示例

设置窗口大小的代码是有效的:

[console]::BufferHeight=9001
[console]::BufferWidth=140
[console]::WindowHeight=50
[console]::WindowWidth=140

但尝试用类似方式设置屏幕位置时失败:

[console]::SetWindowPosition(100,100)

错误输出:

MethodInvocationException: Exception calling "SetWindowPosition" with "2" argument(s):
"The window position must be set such that the current window size fits within the
console's buffer, and the numbers must not be negative. (Parameter 'left')
Actual value was 100."

最简解决方案

通过调用Windows原生API SetWindowPos 直接控制窗口在屏幕上的位置,这是最可靠的实现方式:

设置窗口位置代码

# 导入Win32 API函数
Add-Type @"
using System;
using System.Runtime.InteropServices;

public class Win32 {
    [DllImport("user32.dll")]
    public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);
    
    [DllImport("kernel32.dll")]
    public static extern IntPtr GetConsoleWindow();
}
"@

# 获取当前PowerShell窗口句柄
$hWnd = [Win32]::GetConsoleWindow()

# 将窗口移动到屏幕坐标(100, 100),保持原大小
# 0x0001 = SWP_NOSIZE:不修改窗口宽高
[Win32]::SetWindowPos($hWnd, [IntPtr]::Zero, 100, 100, 0, 0, 0x0001)

获取当前窗口位置代码

如果需要先获取窗口当前位置,可结合GetWindowRect API:

Add-Type @"
using System;
using System.Runtime.InteropServices;

public struct RECT {
    public int Left;
    public int Top;
    public int Right;
    public int Bottom;
}

public class Win32 {
    [DllImport("user32.dll")]
    public static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);
    
    [DllImport("kernel32.dll")]
    public static extern IntPtr GetConsoleWindow();
}
"@

$hWnd = [Win32]::GetConsoleWindow()
[Win32]::GetWindowRect($hWnd, [ref]$rect = [Win32+RECT]::new())

# 输出位置和大小信息
Write-Host "窗口位置:X=$($rect.Left), Y=$($rect.Top)"
Write-Host "窗口大小:宽=$($rect.Right - $rect.Left), 高=$($rect.Bottom - $rect.Top)"

关键说明

  • GetConsoleWindow():获取当前PowerShell控制台窗口的句柄
  • SetWindowPos()参数:
    • X/Y:目标屏幕坐标
    • cx/cy:窗口宽高,设为0配合0x0001标志保持原大小
    • 0x0001(SWP_NOSIZE):仅修改位置,不改变窗口尺寸
    • 如果需要同时调整大小,可修改cx/cy并移除该标志

内容的提问来源于stack exchange,提问作者not2qubit

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 05:59:54