Last active
November 20, 2015 15:24
-
-
Save proxb/d9d9f2090b7bf6bccbac to your computer and use it in GitHub Desktop.
Gets the X and Y position of a Windows given a process name as well as its Width and Height
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<# | |
This will return the rectangle position of a process window. | |
Values of the Rectangle in relation to pixel location on window: | |
Left; // x position of upper-left corner | |
Top; // y position of upper-left corner | |
Right; // x position of lower-right corner | |
Bottom; // y position of lower-right corner | |
#> | |
Function Get-WindowPosition { | |
[cmdletbinding()] | |
Param ( | |
[parameter(ValueFromPipelineByPropertyName=$True)] | |
$ProcessName | |
) | |
Begin { | |
Add-Type @" | |
using System; | |
using System.Runtime.InteropServices; | |
public class Window { | |
[DllImport("user32.dll")] | |
[return: MarshalAs(UnmanagedType.Bool)] | |
public static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect); | |
} | |
public struct RECT | |
{ | |
public int Left; // x position of upper-left corner | |
public int Top; // y position of upper-left corner | |
public int Right; // x position of lower-right corner | |
public int Bottom; // y position of lower-right corner | |
} | |
"@ | |
} | |
Process { | |
$Rectangle = New-Object RECT | |
$Handle = (Get-Process -Name $ProcessName).MainWindowHandle | |
$Return = [Window]::GetWindowRect($Handle,[ref]$Rectangle) | |
If ($Return) { | |
$Height = $Rectangle.Bottom - $Rectangle.Top | |
$Width = $Rectangle.Right - $Rectangle.Left | |
$Size = New-Object System.Management.Automation.Host.Size -ArgumentList $Width, $Height | |
$TopLeft = New-Object System.Management.Automation.Host.Coordinates -ArgumentList $Rectangle.Left, $Rectangle.Top | |
$BottomRight = New-Object System.Management.Automation.Host.Coordinates -ArgumentList $Rectangle.Right, $Rectangle.Bottom | |
If ($Rectangle.Top -lt 0 -AND $Rectangle.Left -lt 0) { | |
Write-Warning "Window is minimized! Coordinates will not be accurate." | |
} | |
[pscustomobject]@{ | |
Size = $Size | |
TopLeft = $TopLeft | |
BottomRight = $BottomRight | |
} | |
} | |
} | |
} | |
Get-Process notepad | Get-WindowPosition | |
<# | |
Size TopLeft BottomRight | |
---- ------- ----------- | |
635,536 5,9 640,545 | |
#> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment