Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...