我希望在我的表单中,宽度是高度的两倍(1:2),并且当我调整大小时也保持这个比例。我该怎么做?谢谢您的帮助,对我的英语表示抱歉 :)
请查看此篇文章:保持宽高比的窗体缩放。
关键在于响应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
}
AnchorStyle.Top | AnchorStyle.Bottom
更多信息请参见:http://msdn.microsoft.com/en-us/vstudio/bb798032.aspx
http://niravdaraniya.blogspot.in/2013/07/how-to-resize-form-in-cnet.html
注册 resize 事件并直接执行以下操作:
this.ClientSize.Width = this.ClientSize.Height * 2;
或者对于完整的表单尺寸(包括边框)
this.Size.Width = this.Size.Height * 2;
private void Form1_Resize(object sender, System.EventArgs e)
{
Control control = (Control)sender;
control.Width = control.Height * 2;
}
你可以使用像onLoad、onClick等事件,在特定条件下进行调整大小。所以基本上这取决于你。
还有一些标准的表单属性,比如高度和宽度,你可以调整这些属性。
例如:
private void frmMain_Load(object sender, EventArgs e)
{
int height = 500;
frmMain.ActiveForm.Height = height;
frmMain.ActiveForm.Width = height / 2;
}