C#中关闭窗体并提示是否关闭

目录

一、在VS中选择C#的Windows窗体应用,建立窗体Form1

二、关闭窗体时弹出确认对话框

(1)先修改Form1.cs

(2)再修改Form1.Designer.cs

三、运行结果


一、在VS中选择C#的Windows窗体应用,建立窗体Form1

        自动生成Form1.cs、Form1.Designer.cs、Program.cs三个C#文件。

二、关闭窗体时弹出确认对话框

        Form1默认的打开方式窗体,编辑源码需要选择“查看代码”,则打开的文件是Form1.cs,否则打开的文件是Form1.cs[设计]。

(1)先修改Form1.cs

//Form1.cs源文件
namespace App1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        //加载窗体Form1
        private void Form1_Load(object sender, EventArgs e)
        {

        }
        //关闭窗体时提示是否关闭
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            DialogResult dr = MessageBox.Show("是否关闭窗体", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
            if (dr == DialogResult.Yes)
            {
                e.Cancel = false;
            }
            else
            {
                e.Cancel = true;
            }
        }
    }
}

(2)再修改Form1.Designer.cs

        在窗体设计器中增加this.FormClosing。这一步很重要缺失不可,否则关闭窗体时没有提示。

namespace App1
{
    partial class Form1
    {
        /// <summary>
        ///  Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        ///  Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        ///  Required method for Designer support - do not modify
        ///  the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            SuspendLayout();
            ///<summary>
            ///关闭窗体Form1弹出提示,询问是否关闭,需要在窗体生成器中增加:
            ///this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Form1_FormClosing);
            /// </summary> 

            AutoScaleDimensions = new SizeF(7F, 17F);
            AutoScaleMode = AutoScaleMode.Font;
            BackColor = SystemColors.HotTrack;
            BackgroundImage = Properties.Resources.mi;
            BackgroundImageLayout = ImageLayout.Stretch;
            ClientSize = new Size(434, 411);
            Name = "Form1";
            Text = "Wen";
            Load += Form1_Load;
            /*this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Form1_FormClosing);//询问是否关闭*/
            FormClosing += Form1_FormClosing;//询问是否关闭,这两条语句任选一种即可
            ResumeLayout(false);
        }

        #endregion
    }
}

三、运行结果

猜你喜欢

转载自blog.csdn.net/wenchm/article/details/132125369