C# 如何取消winform按钮单击事件?
我有一个从System.Windows.Forms.button继承的自定义按钮类 我想在我的winform项目中使用此按钮 该类称为“ConfirmButton”,它显示带有Yes或No的确认消息 但问题是,当用户选择“否”并显示“确认”消息时,我不知道如何停止单击事件 这是我的课堂资料C# 如何取消winform按钮单击事件?,c#,button,onclick,click,C#,Button,Onclick,Click,我有一个从System.Windows.Forms.button继承的自定义按钮类 我想在我的winform项目中使用此按钮 该类称为“ConfirmButton”,它显示带有Yes或No的确认消息 但问题是,当用户选择“否”并显示“确认”消息时,我不知道如何停止单击事件 这是我的课堂资料 using System; using System.ComponentModel; using System.Windows.Forms; namespace ConfirmControlTest {
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;
}
}
}
}
这样为什么要取消单击?不管它,什么也不做。或者只处理
如果(res==System.Windows.Forms.DialogResult.Yes)
`谢谢你的回答,我甚至没有尝试查找覆盖。