How can I make a form have a fixed aspect ratio that is preserved when it is resized?
I know it can be done by overriding OnSizeChanged
and manually modifying the [new] Height/Width, but that causes flicker since it is resized once before the event is called (to a size not matching the aspect ratio) and then resized again (to the correct aspect ratio). Is there a better way?
Resizing of the form can be disabled by setting the FormBorderStyle property of the form to `FixedDialog`, `FixedSingle`, or `Fixed3D`.
Solution 3Right click on your form and go to properties. Then go to Layout options,see there are a property named Size. Change it as your need as width and length wise. Also see a property named StartPosition just after the Size property.
The best option is to use a TableLayoutPanel . Put TableLayoutPanel on the form, set the Dock property to Fill , create required rows and columns and put the controls inside the cells. Of course you need to set Dock/Anchor on the controls inside the cells, so they respond to changes to the cell size.
By dragging either the right edge, bottom edge, or the corner, you can resize the form. The second way you can resize the form while the designer is open, is through the properties pane. Select the form, then find the Properties pane in Visual Studio. Scroll down to size and expand it.
Some code to get you started. The key is to respond to the WM_SIZING message, it allows you to change the window rectangle. This sample is crude, you really want to pay attention to which corner or edge is being dragged by the user, available from m.WParam. The user interface will never be great, you can't really do anything reasonable when the user drags a corner. Making your form's layout flexible enough so you don't care about aspect ration is the real solution. Displaying a scrollbar when the content doesn't fit pretty much lets the user do the Right Thing automatically.
using System.Runtime.InteropServices;
// etc..
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
protected override void WndProc(ref Message m) {
if (m.Msg == 0x216 || m.Msg == 0x214) { // WM_MOVING || WM_SIZING
// Keep the window square
RECT rc = (RECT)Marshal.PtrToStructure(m.LParam, typeof(RECT));
int w = rc.Right - rc.Left;
int h = rc.Bottom - rc.Top;
int z = w > h ? w : h;
rc.Bottom = rc.Top + z;
rc.Right = rc.Left + z;
Marshal.StructureToPtr(rc, m.LParam, false);
m.Result = (IntPtr)1;
return;
}
base.WndProc(ref m);
}
[StructLayout(LayoutKind.Sequential)]
public struct RECT {
public int Left;
public int Top;
public int Right;
public int Bottom;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With