BusyObject: Easily get .NET WinForms apps look busy

.NET, English posts, WinForms


2 min read
Imagine you are working on a .NET WinForms application, and it has many small user tasks which require you to disable all input controls in your form. What happens if each of those also has quite a lot of possible exit points? returning and re-enabling the GUI in all of them is quite a pain. The following code allows you to do this all in just 2 extra lines of code: [csharp]public class BusyObject : IDisposable { private Control m_ctrl; public BusyObject(Control ctrl) { m_ctrl = ctrl; m_ctrl.UseWaitCursor = true; m_ctrl.Enabled = false; } public void Dispose() { m_ctrl.Enabled = true; m_ctrl.UseWaitCursor = false; } }[/csharp] What this code does, is to disable a parent control from its constructor, and use the IDisposable interface to re-enable it once the object is destroyed (e.g., Dispose() is called on it). Encapsulating it with a using statement ensures it will always be destructed, no matter what, so you don't have to worry about releasing the "hold" of your form anymore, also when in need to return prematurely or the like. Usage is very simple: [csharp] using (new BusyObject(this)) { // "this" is the calling form or control /* lengthy operations */ if (foo) return; // This will re-enable the controls parented by "this" /* another lengthy operation */ } // Here all controls parented by "this" are enabled again [/csharp] Always use worker threads where possible, but there are places where user interaction is needed in a specific order, and you need their absolute attention. This is achieved by disabling all irrelevant input controls, and using BusyObject definitely makes this an easy task.

Comments are now closed