一. 自适应布局
窗口在尺寸变化时,会调用OnLayout方法, 所以 , 在form1.cs文件里重写OnLayout方法即可实现自适应
在OnLayout方法中,我们获取一下窗口的宽度和高度,根据窗口的宽度和高度重新设定控件的位置和尺寸
注意: 1. Size是指整个窗口的大小, ClientSize是窗口的用户区域大小
2.有些控件的尺寸是被锁住的,比如textBox的高度,
如下例:
可以看到窗口里的三个控件都随着界面改变位置和大小
下为form1.cs的代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
protected override void OnLayout(LayoutEventArgs levent)
{
base.OnLayout(levent);//调用父类的onlayout
int w = this.ClientSize.Width;
int h = this.ClientSize.Height;
textBox1.Location = new Point(0, 0);
textBox1.Width = w - 80;
textBox1.Height = 22;
button1.Location = new Point(w - 80, 0);
button1.Width = 80;
button1.Height = 22;
pictureBox1.Location = new Point(0, 22);
pictureBox1.Width = w;
pictureBox1.Height = h - 22;
}
}
}
二. 锚点固定
每个控件都有一个通用属性Anchor (锚点)