如何在规模上调整表单大小?C#

Enr*_*ris 2 c# resize scale winforms

我需要在我的形式,宽度是高度的两倍(1:2)当我调整大小 我怎么能这样做?谢谢你的帮助,对不起我的英文:)

Pao*_*tti 6

看看这篇文章:在保持宽高比的同时调整表格大小.

关键是响应WM_SIZING消息,它允许您更改窗口矩形.

public partial class MyForm : Form
{
    public MyForm()
    {
        InitializeComponent();

        // Necessary to take the window frame width/height into account
        this.chromeWidth = this.Width - this.ClientSize.Width;
        this.chromeHeight = this.Height - this.ClientSize.Height;
        this.ClientSize = new System.Drawing.Size(400, 200);
    }

    // ...

    #region Resizer
    private float constantWidth = 2;
    private float constantHeight = 1;

    private int chromeWidth;
    private int chromeHeight;

    // From Windows SDK
    private const int WM_SIZING = 0x214;

    private const int WMSZ_LEFT = 1;
    private const int WMSZ_RIGHT = 2;
    private const int WMSZ_TOP = 3;
    private const int WMSZ_BOTTOM = 6;

    struct RECT
    {
        public int Left;
        public int Top;
        public int Right;
        public int Bottom;
    }

    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
            {
                case WMSZ_LEFT:
                case WMSZ_RIGHT:
                    // Left or right handles, adjust height
                    rc.Bottom = rc.Top + chromeHeight + (int)(constantHeight * w / constantWidth);
                    break;

                case WMSZ_TOP:
                case WMSZ_BOTTOM:
                    // Top or bottom handles, adjust width
                    rc.Right = rc.Left + chromeWidth + (int)(constantWidth * h / constantHeight);
                    break;

                case WMSZ_LEFT + WMSZ_TOP:
                case WMSZ_LEFT + WMSZ_BOTTOM:
                    // Top-left or bottom-left handles, adjust width
                    rc.Left = rc.Right - chromeWidth - (int)(constantWidth * h / constantHeight);
                    break;

                case WMSZ_RIGHT + WMSZ_TOP:
                    // Top-right handle, adjust height
                    rc.Top = rc.Bottom - chromeHeight - (int)(constantHeight * w / constantWidth);
                    break;

                case WMSZ_RIGHT + WMSZ_BOTTOM:
                    // Bottom-right handle, adjust height
                    rc.Bottom = rc.Top + chromeHeight + (int)(constantHeight * w / constantWidth);
                    break;
            }

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

        base.WndProc(ref m);
    }
    #endregion
}
Run Code Online (Sandbox Code Playgroud)

  • 这里要注意的重要一点是,当用户拖动窗口句柄时会发生这种情况,这比响应调整大小(之后发生)提供了更多*更好的体验 (3认同)