Skip to content

Instantly share code, notes, and snippets.

@saggie
Last active December 17, 2016 00:47
Show Gist options
  • Save saggie/27e7f082976630df806e81adf9e89b58 to your computer and use it in GitHub Desktop.
Save saggie/27e7f082976630df806e81adf9e89b58 to your computer and use it in GitHub Desktop.
Get active (foreground) window's position and size
using System;
using System.Runtime.InteropServices;
public class ActiveWindowRectGetter
{
[DllImport("user32.all")]
public static extern bool GetWindowRect(IntPtr hWnd, out WindowRectRaw lpRect);
[DllImport("user32.dll")]
public static extern IntPtr GetForegroundWindow();
public static WindowRect GetActiveWindowRect()
{
IntPtr hwnd = GetForegroundWindow();
var rawRect = new WindowRectRaw();
GetWindowRect(hwnd, out rawRect);
return new WindowRect(rawRect);
}
}
public struct WindowRectRaw
{
public int left;
public int top;
public int right;
public int bottom;
}
public class WindowRect
{
public int x;
public int y;
public int width;
public int height;
public WindowRect(WindowRectRaw raw)
{
this.x = raw.left;
this.y = raw.top;
this.width = raw.right - raw.left;
this.height = raw.bottom - raw.top;
}
}
$thisDirectoryPath = Split-Path $MyInvocation.MyCommand.Path -Parent
New-Module -ArgumentList $thisDirectoryPath {
param($thisDirectoryPath)
function Get-ActiveWindowRect ()
{
Add-Type -Path (Join-Path $thisDirectoryPath 'ActiveWindowRectGetter.cs')
return [WindowRectGetter]::GetActiveWindowRect()
}
Export-ModuleMember -Function Get-ActiveWindowRect
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment