preserve form's aspect ratio upon resize in c#

元气小坏坏 提交于 2019-12-01 19:35:46

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;
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!