WINFORM学习手册——对话框
对话框用于弹出提示消息或者获取用户输入,在弹出对话框后,除非关闭,否则不能返回主窗体
打开上一章的项目,将MainForm.cs里面的代码更改为如下:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WinFrom { public class MainForm : Form//继承Form { private Button MyButton;//创建Button public MainForm() { this.FormClosed += CloseDialog; MyButton = new Button();//实例化Button MyButton.Left = 30;//设置控件离form左边的距离 MyButton.Top = 130;//设置控件离form上边的距离 MyButton.Width = 200;//设置控件的宽度 MyButton.Text = "弹出对话框";//按钮显示名称 MyButton.Click += ShowMessage;//按钮单机事件 this.Controls.Add(MyButton);//将控件加入到form中 } /// <summary> /// 弹出对话框 /// </summary> /// <param name="sender">出发事件的对象</param> /// <param name="e">事件信息</param> private void ShowMessage(object sender, EventArgs e) { MessageBox.Show("这是最简单的弹出框", "弹出对话框"); } /// <summary> /// 关闭提示 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void CloseDialog(object sender, EventArgs e) { //注意提示框的返回值,是DialogResult这个枚举 if (MessageBox.Show("是否关闭窗口", "提示信息", MessageBoxButtons.YesNo)==DialogResult.No) { ((System.ComponentModel.CancelEventArgs)e).Cancel = true; } } } }
执行: