在FormClosing方法中处理Yes/No/Cancel消息框中的取消按钮

5

我在我的窗体的 FormClosing 方法中放置了一个 Yes/No/Cancel Messagebox,现在这个消息框的文本是:是否保存数据?

我不是专业人士,也不知道如何处理用户点击 取消 按钮的情况。实际上,点击取消按钮的结果应该是保持窗体打开状态。
如何在 FormClosing 方法中防止关闭我的窗体?

到目前为止,我写了:

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

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

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

5个回答

12

FormClosing函数有一个布尔参数,如果在函数返回时将其设置为True,则会取消关闭窗体,如果我没记错的话。

编辑:例如,

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

点击这里查看。


10

实际上,我认为你缺少事件处理程序。哦,如果没有事件处理程序,你甚至不能转到那里。你必须像这样添加带有事件处理程序的事件。

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#中编写它并复制粘贴到这里。我只是在这里写的。 :)


7
您可以使用以下内容:

您可以采用如下方式:

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

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

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)
}

如果需要,您可以使用DialogResult类来处理NoCancel按钮的点击事件。

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();
     }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接