How to cancel winform button click event?

喜夏-厌秋 提交于 2019-12-01 06:24:57
Naresh

You need to override the click event.

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

Here's another way to deal with this general kind of problem. (This is not meant as competition to the previous answer, but just food for thought.) Turn the dialogResult property of your button to none then handle it in the code. An OK button example here:

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();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!