Resizing forms while keeping aspect ratio
Published June 27th, 2010 in ProgrammingResizing 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.
Search
About |

Stanimir Stoyanov is a programmer, Microsoft MVP, and Windows enthusiast. Read More...
He's currently working on an array of projects using Visual Studio 2010 on Windows 7.
Latest
- How the Active Directory – Data Store Really Works (Inside NTDS.dit) – Part 1
- Blocking unwanted advertisements and malware with a HOSTS file
- Multithreading with Windows Forms in C#
- Честита Коледа (и поздравления на спечелилите)!
- A simple backup solution using ImageX, a Windows Imaging tool
- Soon: MSDN Ultimate Subscriptions Giveaway
- Decoding FLAC audio files in C#
- Inline Tweet Translator
- Resizing forms while keeping aspect ratio
- Encoding uncompressed audio with FLAC in C#

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.