e.Cancel不起作用

Tor*_*726 3 c#

我有VS 2010并希望通过Yes | No | Cancel对话框取消表单结束事件,但是当我将e.Cancel放入对话框的事件处理程序时,我收到一条错误,上面写着"'System.EventArgs'不包含'Cancel'的定义,也没有扩展方法'Cancel'接受类型'System.EventArgs'的第一个参数可以找到(你是否缺少using指令或汇编引用?)." "取消"一词下面也有一条红线.我在网上看到的一切都说这是取消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;


        }
Run Code Online (Sandbox Code Playgroud)

以下是使用(如果它有所不同):

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;
Run Code Online (Sandbox Code Playgroud)

Ree*_*sey 5

Form.FormClosing使用a FormClosingEventArgs而不是just EventArgs.

你需要使用:

private void displayMessageBox(object sender, FormClosingEventArgs e)
Run Code Online (Sandbox Code Playgroud)

如果您使用较旧的Form.Closing事件,则将其定义为a CancelEventHandler,使用的CancelEventArgs不是EventArgs.

private void displayMessageBox(object sender, CancelEventArgs e)
Run Code Online (Sandbox Code Playgroud)

使用其中任何一个,您就可以:

 e.Cancel = true;
Run Code Online (Sandbox Code Playgroud)


Dan*_*n J 5

的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;
    }
}
Run Code Online (Sandbox Code Playgroud)

此外,e.Cancel是一个属性,您将其称为方法。括号需要删除。