Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
787 views
in Technique[技术] by (71.8m points)

.net - How to stop a Windows Forms Button being clicked twice

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need use this scenario:

public class SingleClickButton : Button
{
        protected override void OnClick(EventArgs e)
        {
                this.Enabled = false;
                RunAsynchronousMethod( CallBack );
                base.OnClick(e);
        }

        void CallBack()
        {
                this.Enabled = true;
        }
}

The "RunAsynchronousMethod" can create new "Thread" or use "ThreadPool.QueueUserWorkItem)".

EDIT:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...