簡體   English   中英

如何取消winform按鈕點擊事件?

[英]How to cancel winform button click event?

我有一個從 System.Windows.Forms.Button 繼承的自定義按鈕類。

我想在我的 winform 項目中使用這個按鈕。

這個類被稱為“ConfirmButton”,它顯示帶有 Yes 或 No 的確認消息。

但問題是,當用戶選擇“否”並帶有確認消息時,我不知道如何停止單擊事件。

這是我的課程來源。

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

            }
        }
    }
}

如果用戶從確認消息中選擇否,則按鈕單擊事件不應再觸發。

您需要覆蓋點擊事件。

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

這是處理這種一般問題的另一種方法。 (這並不意味着與上一個答案的競爭,而只是值得思考。)將按鈕的 dialogResult 屬性設置為 none 然后在代碼中處理它。 此處為 OK 按鈕示例:

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

我想你可以使用return

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)
            {
                return;

            }
        }
    }
}

像那樣

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM