4

我在表单的FormClosing方法中放置了一个是/否/取消消息框。现在这是消息框文本:您要保存数据吗?

如果用户单击取消按钮,我不是专业人士,不知道如何处理?确切地说,单击取消按钮的结果必须是表单保持打开状态。
如何防止在FormClosing方法中关闭我的表单?

我写了到目前为止:;)

DialogResult dr = MessageBoxFarsi.Show("Do You Want to Save Data?","",MessageBoxButtons.YesNoCancel,MessageBoxIcon.Warning);

//...
else if (dr == DialogResult.Cancel)
{
    ???
}

请帮我完成我的代码!
谢谢

4

5 回答 5

12

FormClosing 有一个布尔参数,如果在函数返回时设置为 True,将取消关闭表单 IIRC。

编辑:例如,

private void Form1_FormClosing(Object sender, FormClosingEventArgs e) {
    // Set e.Cancel to Boolean true to cancel closing the form
}

见这里

于 2009-08-09T23:39:15.883 回答
9

实际上,我认为您缺少事件处理程序,哦,即使没有偶数处理程序,您也无法转向。您必须使用这样的事件处理程序添加事件。

private void myform_Closing(object sender, FormClosingEventArgs e) 
{
    DialogResult dr = MessageBoxFarsi.Show("Do You Want to Save Data?","",MessageBoxButtons.YesNoCancel,MessageBoxIcon.Warning)

    if (dr == DialogResult.Cancel) 
    {
        e.Cancel = true;
        return;
    }
    else if (dr == DialogResult.Yes)
    {
        //TODO: Save
    }
}

//now add a default constructor 
public myform()  // here use your form name.
{
    this.FormClosing += new FormClosingEventHandler(myform_Closing); 
}

如果这段代码中有一些拼写错误,请见谅,因为我不是用 c# 编写的,所以在这里复制粘贴。我只是在这里写的。:)

于 2011-07-14T17:20:29.193 回答
7

你可以有类似下面的东西:

if(dr == DialogResult.Cancel)
{
    e.Cancel = true;
}
else if(dr == DialogResult.Yes)
{
    //Save the data
}

上面的代码应该只在您选择是或否时关闭表单,并在您选择是时保存数据。

于 2009-08-09T23:47:16.070 回答
1

你可以试试这个:

if (MessageBox.Show("Are you sure you want to quit?", "Attention!!", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning) == DialogResult.Yes)
{
   //this block will be executed only when Yes is selected
   MessageBox.Show("Data Deleted", "Done", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}
else
{
  //this block will be executed when No/Cancel is selected
  //the effect of selecting No/Cancel is same in MessageBox (particularly in this event)
}

如果需要相同,您可以使用类对NoCancel按钮单击进行操作DialogResult

于 2018-08-22T08:22:20.410 回答
0

你应该试试这个功能

public DialogResult msgClose(string msg)
{
     return MessageBox.Show(msg, "Close", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
}

并像这样使用。

private void frm_FormClosing(object sender, FormClosingEventArgs e)
{
     if (conn.msgClose("Application close?") == DialogResult.No)
         e.Cancel = true;
     else
     {
         this.Close();
     }
}
于 2017-07-31T00:35:55.067 回答