我有VS 2010,想通过Yes | No | cancel对话框取消表单关闭事件,但当我在对话框的事件处理程序中放入e.cancel时,我收到一个错误,上面写着"System.EventArgs"不包含"Cancel"的定义,并且找不到接受"System.EventArgs"类型的第一个参数的扩展方法"Cancel)(您是否缺少using指令或程序集引用?)。"Cancel(取消)"一词下面有一条红线。我在网上读到的所有内容都表明,这是取消FormClosing事件的唯一方法。我在VS2008中测试了代码,它也做了同样的事情。
事件处理程序的代码如下:
private void displayMessageBox(object sender, EventArgs e)
{
DialogResult result = MessageBox.Show("Do you want to save the changes to the document before closing it?", "MyNotepad",MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning);
if (result == DialogResult.Yes)
{
saveToolStripMenuItem_Click(sender, e);
}
else if (result == DialogResult.No)
{
rtbMain.Clear();
this.Text = "Untitled - MyNotepad";
}
else if (result == DialogResult.Cancel)
{
// Leave the window open.
e.Cancel() = true;
}
以下是用法(如果有区别的话):
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
Form.FormClosing使用FormClosingEventArgs
而不是仅使用EventArgs
。
您需要使用:
private void displayMessageBox(object sender, FormClosingEventArgs e)
如果使用旧的Form.Clossing事件,则会将其定义为CancelEventHandler
,它使用CancelEventArgs
,而不是EventArgs
。
private void displayMessageBox(object sender, CancelEventArgs e)
使用其中任何一个,你可以做:
e.Cancel = true;
FormClosing事件有自己的EventArgs子类,您应该将其作为事件处理程序的参数:
private void displayMessageBox(object sender, FormClosingEventArgs e)
{
DialogResult result = MessageBox.Show("Do you want to save the changes to the document before closing it?", "MyNotepad", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning);
if (result == DialogResult.Yes)
{
saveToolStripMenuItem_Click(sender, e);
}
else if (result == DialogResult.No)
{
rtbMain.Clear();
this.Text = "Untitled - MyNotepad";
}
else if (result == DialogResult.Cancel)
{
// Leave the window open.
e.Cancel = true;
}
}
此外,e.Cancel
是一个属性,您调用它就像调用方法一样。括号需要去掉。
在方法签名中使用FormClosingEventArgs
类型:
private void displayMessageBox(object sender, FormClosingEventArgs e)
和:
e.Cancel = true;
或者将引用强制转换为访问它的类型:
((FormClosingEventArgs)e).Cancel = true;
这很容易>>
使用表格关闭事件:
private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
{
displayMessageBox(this, e);
}
private void displayMessageBox(object sender, FormClosingEventArgs e)
{
DialogResult result = MessageBox.Show("Do you want to save the changes to the document before closing it?",
"MyNotepad", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning);
if (result == DialogResult.Yes)
{
saveToolStripMenuItem_Click(sender, e);
}
else if (result == DialogResult.No)
{
rtbMain.Clear();
this.Text = "Untitled - MyNotepad";
}
else if (result == DialogResult.Cancel)
{
// Leave the window open.
e.Cancel = true;
}
}