开发者

Easiest way to disable Form while worker thread spins?

When I have a WinForms app that needs to do some heavy lifting in the background but only ever one task at at time (the usual), the general procedure is the same:

  • Set UI to "working" status (disable button to prevent subsequent presses, display operation progress, maybe pop up separate status form on top of main form...)
  • newThread.Start();
  • Set UI back to user-interactable state when finished or canceled

The problem is, I always end up wiring it all up by hand. If I go the route of disabling certain buttons, making the form confirm when the user tries to close it, etc... there's really no way around that, since each form is different. But sometimes it's just not worth it to spend the time writing all those specifics and all I want to do is stop the user from clicking anyth开发者_开发知识库ing and show some visual indication that the application is working.

Is there an easy way to set the UI to a non-interactable "working" status, sort of a like a lightbox does in web interfaces?

Criteria:

  • Least amount of code wins. (I'm lazy.)
  • User should no longer be able to interact with the form.
    • Form can be completely non-interactable, partially non-interactable, whatever keeps the user relatively contained.
    • Option to cancel operation is not required... that can be added later depending on how much time I want to spend on user experience.

If only there were a UI counterpart to BackgroundWorker...


yourForm.Enabled = false;

I don't think it can be made shorter ;)

This will disable all controls on the form, but you can still update a progress bar or a label if necessary.


Another way:

2nd form, call ShowDialog() from first. Handle Background Worker by passing arguments to 2nd form, etc.

This will sit in front of your main form essentially disabling it.

On the 2nd form, you can put a busy graphic and a cancel button. No way user can get at the other form unless they cancel out of the 2nd form dialog.

Re-using the 2nd form dialog is also possible.


I had to do it this way:

this.Enabled = false;


I know is a little too late for this but here you have it.

Using this.Enabled = false; disables the window so the UI freeze not allowing to minimize and move the form, so I use this instead.

                foreach (Control control in this.Controls)
            {
                control.Enabled = false;
            }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜