我需要一些有关窗口窗体调整大小的帮助,这个 Form1 默认打开,大小为 800x600,但它以编程方式更改其大小,使用下面的代码我试图使用新的保持窗口窗体的外观大小值,但我的问题是,在调整窗口窗体大小时,它失去了它的预期方面,我不知道如何修复它。
举个简单的例子,当前窗口大小是宽度 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
纵横比是一个比例,意思是height/width
的结果应该是要保持的纵横比的相同值。除非高度和宽度是相同的值(即正方形),否则简单地改变相同的量不会保持纵横比。
因此,您需要更改高度(或宽度),方法是首先获取纵横比(即 height/width
),然后将该值乘以高度以获得宽度(或反之亦然)。
const double Ratio = height / width;
...
height = height + 50; // This works the same if you change the 'width'
width = height * Ratio;
我是一名优秀的程序员,十分优秀!