Resizing a form while keeping aspect ratio is useful in many cases, like video playback or vector graphics. This way, the window can be resized while retaining the original ratio and avoiding the use of letterboxing or pillarboxing.

What’s needed is for the window function to be overriden (WndProc) and pre-process the target window rectangle used by the WM_SIZING message.

The new destination rectangle is calculated by taking into account the resizing handle and the window chrome size (title height, border width, etc.).

protected override void WndProc(ref Message m)
{
    if (m.Msg == WM_SIZING)
    {
        RECT rc = (RECT)Marshal.PtrToStructure(m.LParam, typeof(RECT));

        int w = rc.Right - rc.Left - chromeWidth;
        int h = rc.Bottom - rc.Top - chromeHeight;

        switch (m.WParam.ToInt32()) // Resize handle
        {

           // …

        }

        Marshal.StructureToPtr(rc, m.LParam, true);
    }

    base.WndProc(ref m);
}

You can find the full C# source code here, including a test program. The aspect ratio and initial client size is set to 16:9.


One Response to “Resizing forms while keeping aspect ratio”  

  1. 1 Lorenz Cuno Klopfenstein

    Very nice sample. :)
    I’m using it to improve the aspect ratio-constrained resizing of OnTopReplica and have been able to fix a couple of quirks thanks to your sample.

Leave a Reply