C# Programming > Windows Forms

C# Aspect Ratio Form

Aspect Ratio Form

We can easily create a C# Windows Form that maintains its aspect ratio when it is resized. A constant ratio between the width and height of a Windows Form is useful for many applications such as picture and video programs.

In order to prevent flickering when adjusting the width and height of the Windows Form, we are going to work with Windows messages in the C# code.

Maintain Aspect Ratio

First what is aspect ratio? Aspect ratio is the ratio of something's width to its height. Aspect ratio is a term commonly used for image and video dimensions, but it can apply to any type of dimensions (in our case .NET Windows Forms). It is commonly written in the format width:height, for example 6:4 aspect ratio.

To maintain the aspect ratio of the Windows Form in C# while its being resized means adjusting either the width or height accordingly when the width or height is being resized. So if the width is being increased or decreased, we must programmatically adjust the height to maintain the aspect ratio, that is to keep the ratio of the new width to the height the same.

The math is simple. It is a simple ratio:

C# Form Aspect Ratio

Thus, by cross multiplying, the new width of our Windows Form would be (ratio width * Form height) / ratio height
Similarly the new height of the Form is given by (ratio height * Form width) / ratio width

All the heights and width can be confusing when you go to write the C# code, but just remember the ratio above and it'll be easier to keep them straight.

Applying Aspect Ratio to Windows Forms

Much like we intercepted Windows message in our Windows 7 Style Form, to keep the aspect ratio of a Windows Form we are going to intercept the resizing Windows messages. This is done by overriding WndProc.

Here is a list of the constants that we need for this algorithm:

WM_SIZING = 0x214

The first one is the way our C# application can tell when the Form is being resized. The rest of the constants tell us exactly which side of the Form is being resized. Note that for corners the edges combine. So for example, the lower left corner would be resizing the right and bottom parts of the form and thus be 2 + 6 = 8.

The advantage of using WndProc instead of Windows Form events is that we can prevent the Form from flickering. Resize events in .NET are called until after the resizing has been applied, so modifying size in an event produces flickering.

Make sure to download the sample C# application. Notice how no matter where you resize the Form from, the aspect ratio is maintained. A quick peek at the source code shows how either the height or width is adjusted depending on which side of the Form was being resized. Another cool thing is that the Form can still be maximized to fill the entire screen without any problems.

Back to C# Article List