如何取消winform按钮点击事件?

Jos*_*Son 5 c# click onclick button

我有一个从System.Windows.Forms.Button继承的自定义按钮类.

我想在winform项目中使用这个按钮.

此类称为"ConfirmButton",它显示带有"是"或"否"的确认消息.

但问题是,当用户选择否带有确认消息时,我不知道如何停止点击事件.

这是我的班级来源.

using System;
using System.ComponentModel;
using System.Windows.Forms;

namespace ConfirmControlTest
{
    public partial class ConfirmButton : System.Windows.Forms.Button
    {
        public Button()
        {
            InitializeComponent();

            this.Click  += Button_Click;
        }

        void Button_Click(object sender, EventArgs e)
        {
            DialogResult res    = MessageBox.Show("Would you like to run the command?"
                , "Confirm"
                , MessageBoxButtons.YesNo
                );
            if (res == System.Windows.Forms.DialogResult.No)
            {
                // I have to cancel button click event here

            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

如果用户从确认消息中选择"否",则不再触发按钮单击事件.

小智 7

您需要覆盖点击事件。

class ConfirmButton:Button
    {
    public ConfirmButton()
    {

    }

    protected override void OnClick(EventArgs e)
    {
        DialogResult res = MessageBox.Show("Would you like to run the command?", "Confirm", MessageBoxButtons.YesNo
            );
        if (res == System.Windows.Forms.DialogResult.No)
        {
            return;
        }
        base.OnClick(e);
    }
}
Run Code Online (Sandbox Code Playgroud)


Jef*_*eff 5

这是处理此类一般问题的另一种方法。(这并不是为了与之前的答案竞争,而是为了思考。)将按钮的dialogResult属性设置为none,然后在代码中处理它。这里有一个“确定”按钮示例:

private void OKUltraButton_Click(object sender, Eventargs e)
{
    {
    //Check for the problem here, if true then...
        return;
    }

    //Set Dialog Result and manually close the form
    this.DialogResult = System.Windows.Forms.DialogResult.OK;
    this.Close();
}
Run Code Online (Sandbox Code Playgroud)