用 PowerShell 指定窗口的位置和大小

我想尝试通过命令来指定应用程序窗口的位置和大小,所以我试了一下。

本次参考了以下代码进行实现。请参考代码部分的节。

    win7 powershell script to automatically resize a minecraft window for 1280×720 HD fraps recording. · GitHub

尝试使用

获取位置和尺寸

你可以使用Get-WindowRect命令获取左上角的位置和大小。

PS> Get-WindowRect * | ft

Name            X      Y Width Height
----            -      - ----- ------
EXCEL         650     92   702    525
powershell     38    131   589    615
001.png

指定位置和大小

可以使用Move-WindowRect指定窗口的左上位置和大小,如下所示。

PS> Move-WindowRect powershell 650 92 702 525
PS> Move-WindowRect Excel 38 131 589 615
PS> Get-WindowRect * | ft
Name            X      Y Width Height
----            -      - ----- ------
EXCEL          38    131   589    615
powershell    650     92   702    525
002.png

保存和恢复位置和大小

通过Export-WindowRect命令,将每个窗口的当前位置和大小导出到csv文件中,然后可以使用Import-WindowRect命令读取该文件,从而恢复每个窗口的位置和大小。

PS> Export-WindowRect .\wr.csv
PS> cat .\wr.csv
"Name,"X","Y","Width","Height"
"EXCEL,"38","131","589","615"
"powershell,"650","92","702","525"
PS> 
PS> # 適当にウィンドウを動かして、大きさを変える
PS> 
PS> Import-WindowRect .\wr.csv

代码

filter Import-WindowRect ($Path)
{Import-Csv $Path | %{Move-WindowRect $_.Name $_.X $_.Y $_.Width $_.Height}}

filter Export-WindowRect ($Path)
{Get-Process -Name * | %{Get-WindowRect $_.Name} | Export-Csv $Path -Encoding UTF8 -NoTypeInformation}

filter Move-WindowRect
{
  Param
  (
    [String]$Name,
    [Int]$X = 0,
    [Int]$Y = 0,
    [Int]$Width = 400,
    [Int]$Height = 300
  )

  Get-Process -Name $Name | ?{$_.MainWindowTitle -ne ""} | %{
    [Win32]::MoveWindow($_.MainWindowHandle, $X, $Y, $Width, $Height, $true)
  } | Out-Null
}

filter Get-WindowRect ([String]$Name)
{
  Get-Process -Name $Name | ?{$_.MainWindowTitle -ne ""} | %{
    $rc = New-Object RECT
    [Win32]::GetWindowRect($_.MainWindowHandle, [ref]$rc) | Out-Null
    ConvertTo-Rect2 $_.Name $rc
  }
}


# Helper
# ------

filter ConvertTo-Rect2 ($name, $rc)
{
  $rc2 = New-Object RECT2

  $rc2.Name = $name
  $rc2.X = $rc.Left
  $rc2.Y = $rc.Top
  $rc2.Width = $rc.Right - $rc.Left
  $rc2.Height = $rc.Bottom - $rc.Top

  $rc2
}

# C#
# --

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

  public class Win32 {
    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    public static extern bool MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint);

    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    public static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);
  }

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

  public struct RECT2
  {
    public string Name;
    public int X;
    public int Y;
    public int Width;
    public int Height;
  }
"@
bannerAds