防止关闭主表格 [英] Prevent Closing Main Form

查看:65
本文介绍了防止关闭主表格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个说Form1的表单,我需要做的是,当用户按下表单标题栏上的关闭"按钮时,应该允许他选择是否退出;如果他按下否",则应用程序应该继续运行. >
从退出菜单或按钮中可以很好地使用此功能,但是人们倾向于按标题栏上的关闭按钮



我编写了以下代码:---

I have a form say Form1 What I have to do is when user presses Close button on title bar of the form it should allow him choice whether to exit or not;If he presses No the application should keep running.

This functionality would work fine example from Exit menu or button but people tend to press close button on title bar



I have written the following code:---

private void Form1_FormClosing(object sender, FormClosedEventArgs e)
{
DialogResult dr = MessageBox.Show("Do you want to quit", "Exit",MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk);
           if (dr == DialogResult.No)
           {
               return;
               //Code Trying to prevent closing of form but failed

           }
}



给出以下内容毫无意义:-



it''s no meaning to give:-

if (dr == DialogResult.Yes)
           {
               this.Close();
                //Form will close even without this...

           }





在此先感谢.....



Thanks in Advance.....

推荐答案

尝试:
private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
    {
    if (MessageBox.Show("Close?", "Close main form", MessageBoxButtons.YesNo) == DialogResult.No)
        {
        e.Cancel = true;
        }
    }


当您获得FormClosing事件时,该表单已经关闭,例如,如果在事件外部调用了this.Close(),则您的事件将被解雇.

实际上,您似乎正在使用FormClosed事件,到现在为止阻止表单关闭为时已晚.您要使用FormClosing事件,该事件采用FormClosingEventArgs,可以使用该事件停止关闭表单或更改CloseReason属性.

然后,您可以停止关闭购买设置e.Cancel = true
When you get the FormClosing event the then the form is already going to close, if you called this.Close() outside of the event for example, then your event would be fired.

It actually seems like your using the FormClosed event, by this point it''s too late to stop the form from closing. You want to use the FormClosing event which takes the FormClosingEventArgs which you can use to stop the form from closing, or change the CloseReason property.

You can then stop the form from closing buy setting e.Cancel = true


这篇关于防止关闭主表格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆