1.限制窗体的大小
知识点
(1)Width属性:用于获取和设置窗体的宽度
(2)Height属性:用于获取和设置窗体的高度
(3)FormBorderStyle属性:用于获取和设置窗体的边框样式
- None:无边框
- FixedSingle:固定的单行边框
- Fixed3D:固定的三维边框
- FixedDialog:固定的对话框样式的粗边框
- Sizable:可调整大小的边框
- FixedToolWindow:不可调整大小的工具窗口边框,工具窗口不会显示在任务栏中,也不会显示在当用户按Alt+Tab键时出现的窗口中。
- SizableToolWindow:可调整大小的工具窗口边框,工具窗口不会显示在任务栏中,也不会显示在当用户按Alt+Tab键时出现的窗口中。
private void Form1_Load(object sender, EventArgs e)
{
this.Width = 300;
this.Height = 150;
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
}
2.根据桌面大小调整窗体大小
要想根据桌面大小调整窗体的大小,重点在于获取桌面的大小。
Screen类表示单个系统上的一个或多个显示设备,其PrimaryScreen属性用来获取主显示,该属性返回一个Screen对象,而调用Screen对象的WorkingArea属性可以获取显示器的工作区(Rectangle)。
/// <summary>
/// 获取桌面大小
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, EventArgs e)
{
int DeskWidth = Screen.PrimaryScreen.WorkingArea.Width;
int DeskHeight = Screen.PrimaryScreen.WorkingArea.Height;
txtDeskWidth.Text = DeskWidth.ToString();
txtDeskHeight.Text = DeskHeight.ToString();
}
/// <summary>
/// 计算窗体大小
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button2_Click(object sender, EventArgs e)
{
double bfb = double.Parse(textBox1.Text.Trim())/100;
int DeskWidth = int.Parse(txtDeskWidth.Text.Trim());
int DeskHeight = int.Parse(txtDeskHeight.Text.Trim());
int FormWidth = Convert.ToInt32(Math.Floor(DeskWidth*bfb));
int FormHeight = Convert.ToInt32(Math.Floor(DeskHeight * bfb));
txtFormWidth.Text = FormWidth.ToString();
txtFormHeight.Text = FormHeight.ToString();
}
/// <summary>
/// 设置窗体大小
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button3_Click(object sender, EventArgs e)
{
this.Width = int.Parse(txtFormWidth.Text.Trim());
this.Height = int.Parse(txtFormHeight.Text.Trim());
}
3.自定义最大化,最小化,关闭按钮
在制作程序时,为了使用户界面更美观,一般都自己设计窗体的外观,已经窗体的最大化,最小化和关闭按钮。
知识点
(1)资源文件
在加载图片时,如果是以本地资源进行加载,那么在运行可执行文件时,必须在当前目录下存放指定的图片,这样会给用户带来不必要的麻烦。为了解决这一问题,本实例利用资源文件来存储相关的图片。
- 将文件存入资源文件中
在解决方案面板中打开Properties中的Resources.resx文件
在"添加资源"下拉框中选择"添加现有文件",弹出将现有文件添加到资源中窗体,在该窗体中将指定的图片添加到资源文件中
- 读取资源文件中的图片
pictureBox.Image=Properties.Resources.最大化按钮;
(2)WindowState属性
该属性用于获取或设置窗体的窗口状态
- Maximized:最大化的窗口
- Minimized:最小化的窗口
- NORmal;默认大小的窗口
/// <summary>
/// 设置窗体的最大化,最小化,和关闭按钮
/// </summary>
/// <param name="frm_Tem"></param>
/// <param name="n"></param>
public void FrmClickMeans(Form frm_Tem, int n)
{
switch (n)
{
case 0:
frm_Tem.WindowState = FormWindowState.Minimized;
break;
case 1:
if (frm_Tem.WindowState == FormWindowState.Maximized)
{
frm_Tem.WindowState = FormWindowState.Normal;
}
else
{
frm_Tem.WindowState = FormWindowState.Maximized;
}
break;
case 2:
frm_Tem.Close();
break;
}
}
4.禁止改变窗体的大小
private void button4_Click(object sender, EventArgs e)
{
this.MaximizeBox = false; //禁用"最大化"按钮
this.FormBorderStyle = FormBorderStyle.FixedDialog; //设置窗体边框样式为对话框样式
}