我需要一些关于窗体调整大小的帮助,Form1默认以800x600的大小打开,但它会使用编程方式更改大小。下面的代码可以保持窗体的纵横比,但是当重新调整窗口大小时,纵横比会失效,我无法解决这个问题。
举个例子,当前窗口大小为宽度800,高度600,如果重新调整大小,应该保持纵横比。比如说,如果窗口被调整为宽度850,那么我期望高度是650。对吗?
举个例子,当前窗口大小为宽度800,高度600,如果重新调整大小,应该保持纵横比。比如说,如果窗口被调整为宽度850,那么我期望高度是650。对吗?
public Form1()
{
InitializeComponent();
// Default Window Size
ClientSize = new Size(800, 600);
chromeWidth = Width - ClientSize.Width;
chromeHeight = Height - ClientSize.Height;
}
// Window form Size changes programatically from a size handler, updating "ClientSize".
//////////////////////////// Resize /////////////////////////////////////
#region Resizer
private float constantWidth = 1;//16;
private float constantHeight = 1;//9;
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 System.Windows.Forms.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