Get the Width and Height of Any Window in C# with GetWindowRect

For your own WinForms form you don’t need the Windows API at all: Bounds, Size and ClientSize already hold the numbers. GetWindowRect from user32.dll is for the other cases, when the window belongs to another application or all you have is a window handle (HWND), for example from Process.MainWindowHandle.

This is Windows-only. The example below is a console app, so the project needs the Windows target framework and, because it uses the [LibraryImport] source generator, unsafe code enabled:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net8.0-windows</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
    <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
  </PropertyGroup>
</Project>

In a WinForms project you would also have <UseWindowsForms>true</UseWindowsForms>; the P/Invoke code is the same.

Measure the foreground window

The program waits three seconds so you can click on another window, then prints that window’s position and size.

using System.Runtime.InteropServices;

Console.WriteLine("Click on another window. Measuring in 3 seconds...");
Thread.Sleep(3000);

IntPtr hWnd = NativeMethods.GetForegroundWindow();

if (NativeMethods.GetWindowRect(hWnd, out RECT rect))
{
    Console.WriteLine($"Position: {rect.Left}, {rect.Top}");
    Console.WriteLine($"Size: {rect.Width} x {rect.Height}");
}
else
{
    Console.WriteLine($"GetWindowRect failed with error {Marshal.GetLastPInvokeError()}");
}

[StructLayout(LayoutKind.Sequential)]
internal struct RECT
{
    public int Left;
    public int Top;
    public int Right;
    public int Bottom;

    public readonly int Width => Right - Left;
    public readonly int Height => Bottom - Top;
}

internal static partial class NativeMethods
{
    [LibraryImport("user32.dll")]
    internal static partial IntPtr GetForegroundWindow();

    [LibraryImport("user32.dll", SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    internal static partial bool GetWindowRect(IntPtr hWnd, out RECT lpRect);
}

RECT stores the four edges, not a size, so width is Right - Left and height is Bottom - Top. The coordinates are screen coordinates, which means Left and Top can be negative on a multi-monitor setup where a monitor sits to the left of or above the primary one.

The Win32 BOOL is a 4-byte integer, not a C# bool. The older [DllImport] assumes that by default, but [LibraryImport] has no default for bool and refuses to compile without the MarshalAs(UnmanagedType.Bool) attribute.

To measure a specific application instead of the foreground window, get its handle from the process:

using System.Diagnostics;

Process? notepad = Process.GetProcessesByName("notepad").FirstOrDefault();
IntPtr hWnd = notepad?.MainWindowHandle ?? IntPtr.Zero;

MainWindowHandle is IntPtr.Zero when the process has no visible main window, and GetWindowRect then fails with error 1400 (invalid window handle).

The size includes an invisible border

On Windows 10 and 11, GetWindowRect returns a rectangle that is a few pixels larger than what you see. The extra space is the invisible resize border around the window. If you are lining up windows or taking a screenshot, ask the Desktop Window Manager for the visible frame instead:

internal static partial class Dwm
{
    internal const int DWMWA_EXTENDED_FRAME_BOUNDS = 9;

    [LibraryImport("dwmapi.dll")]
    internal static partial int DwmGetWindowAttribute(
        IntPtr hwnd, int dwAttribute, out RECT pvAttribute, int cbAttribute);
}
int hr = Dwm.DwmGetWindowAttribute(
    hWnd, Dwm.DWMWA_EXTENDED_FRAME_BOUNDS, out RECT frame, Marshal.SizeOf<RECT>());

if (hr == 0)
{
    Console.WriteLine($"Visible size: {frame.Width} x {frame.Height}");
}

The function returns an HRESULT, where 0 means success.

DPI scaling

If your process is not DPI aware, Windows scales the values it hands back, so on a monitor set to 150% the numbers will not match physical pixels. DWMWA_EXTENDED_FRAME_BOUNDS is always in physical pixels, which makes the two results disagree on such a system. When exact pixels matter, declare per-monitor DPI awareness: in WinForms with <ApplicationHighDpiMode>PerMonitorV2</ApplicationHighDpiMode> in the project file, in a console app through an application manifest.

On .NET Framework

[LibraryImport] needs .NET 7 or later. On older runtimes use [DllImport], which takes the same parameter types and does not need unsafe code:

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

There, read the error with Marshal.GetLastWin32Error().

Related examples

Leave a Comment