c# - Adjust controls to match form resize in Visual Studio C# 2019?
问题描述
Normally, when I shrink my form, it just covers stuff up. How do I make it so that the content adjusts position when the form is resized?
The only answers to this question are from 9-10 years ago and refer to properties I can't find.
Edit: I think I might not be using winforms, the specific project type is "Windows Forms App (.NET Framework), is that not winforms?
解决方案
您可以创建一个新类来在调整窗体大小时调整控件的位置。
public partial class Form1 : Form
{
AutoSizeFormClass asc = new AutoSizeFormClass();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
asc.controllInitializeSize(this);
}
private void Form1_SizeChanged(object sender, EventArgs e)
{
asc.controlAutoSize(this);
}
}
class AutoSizeFormClass
{
public struct controlRect
{
public int Left;
public int Top;
public int Width;
public int Height;
}
public List<controlRect> oldCtrl;
public void controllInitializeSize(Form mForm)
{
oldCtrl = new List<controlRect>();
controlRect cR;
cR.Left = mForm.Left; cR.Top = mForm.Top; cR.Width = mForm.Width; cR.Height = mForm.Height;
oldCtrl.Add(cR);
foreach (Control c in mForm.Controls)
{
controlRect objCtrl;
objCtrl.Left = c.Left; objCtrl.Top = c.Top; objCtrl.Width = c.Width; objCtrl.Height = c.Height;
oldCtrl.Add(objCtrl);
}
}
public void controlAutoSize(Form mForm)
{
float wScale = (float)mForm.Width / (float)oldCtrl[0].Width;
float hScale = (float)mForm.Height / (float)oldCtrl[0].Height;
int ctrLeft0, ctrTop0, ctrWidth0, ctrHeight0;
int ctrlNo = 1;
foreach (Control c in mForm.Controls)
{
ctrLeft0 = oldCtrl[ctrlNo].Left;
ctrTop0 = oldCtrl[ctrlNo].Top;
ctrWidth0 = oldCtrl[ctrlNo].Width;
ctrHeight0 = oldCtrl[ctrlNo].Height;
c.Left = (int)((ctrLeft0) * wScale);
c.Top = (int)((ctrTop0) * hScale);
ctrlNo += 1;
}
}
}
测试结果:
推荐阅读
- python - Django:从另一个查询集中获取 ForeignKey 元素的查询集
- c# - IdentityServer4 的 Windows 身份验证
- c - Convert from struct (of char[]) to binary
- python - aws EMR中的python虚拟环境
- python - 当切片很小时避免重叠
- graphql - GraphQL 对象类型的多个联合类型的成员?
- java - 如何在 .Net Core 中使用 RSA 加密数据并在 Java 中解密?
- javascript - jQuery .on('click') 事件仅在单击时工作一次
- plotly - 在 Plotly 中用两个 y 轴绘制一个系列
- django - 如何在 Django 中反转包含模式路径