问题描述
我有一个Windows窗体按钮,提交Web请求表单上。我希望能够禁用按钮,它首先点击,然后重新启用它,当我得到回应的时候。我没有太多的控制权,code,它被调用以及它是如何被调用,所以我可以玩的是巴顿的事件,我也可以创建自己的按钮,它继承按钮,如下所示:
I've got a Windows Forms Button on a Form which submits a web request. I want to be able to disable the button when it is first clicked and then re-enable it when I get a response. I don't have much control over the code that is being called and how it is being called so all I can play around with are Button events or I can create my own button that inherits from Button like so:
public class SingleClickButton : Button
{
protected override void OnClick(EventArgs e)
{
bool wasEnabled = this.Enabled;
this.Enabled = false;
if (wasEnabled)
{
base.OnClick(e);
}
}
}
我必须调用基OnClick方法最后的按钮将不会关闭,直到Web请求已完成。
I have to call the base OnClick method last as the button won't disable until the web request has completed.
我遇到的问题是,如果用户不点击多次的点击事件似乎建立和都还在执行。有可能的方式来取消所有排队的事件?或者是有一个更简单的解决我的问题?
The problem I am having is that if the user does click multiple times the click events seem to build up and are all still executed. Is there maybe a way to cancel all queued events? Or is there a far simpler solution to my problem?
推荐答案
您需要使用此方案:
public class SingleClickButton : Button
{
protected override void OnClick(EventArgs e)
{
this.Enabled = false;
RunAsynchronousMethod( CallBack );
base.OnClick(e);
}
void CallBack()
{
this.Enabled = true;
}
}
在RunAsynchronousMethod可以创建新的主题,或者使用ThreadPool.QueueUserWorkItem)。
The "RunAsynchronousMethod" can create new "Thread" or use "ThreadPool.QueueUserWorkItem)".
编辑:
public class SingleClickButton : Button {
protected override void OnClick(EventArgs e) {
this.Enabled = false;
RunAsynchronousMethod( CallBack );
base.OnClick(e);
}
void CallBack() {
this.Enabled = true;
}
void RunAsynchronousMethod( Action callBack ) {
// there you can use ThreadPool or Thread
ThreadPool.QueueUserWorkItem( this.Worker, callBack );
}
void Worker( object callBack ) {
try {
// some operations
}
finally {
// after operations was proceeded, the callback function will
// be called
((Action)callBack)();
}
}
}
这篇关于如何停止Windows窗体按钮被点击两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!