Daily Archives: February 22, 2008

Tip: Easily Automating use of WaitCursor

This is really simple and probably common, but it’s a useful tip anyway.

Say you need to set a form’s cursor to the wait cursor while you accomplish something.

You would do something like this:

this.Cursor = Cursors.WaitCursor;
 
//do something
 
this.Cursor = Cursors.Default;

Of course, what if “do something” throws an exception? Then your cursor won’t be set back to the default.

So let’s wrap it in try-finally.

try
{
    this.Cursor = Cursors.WaitCursor;
    //do something
}
finally
{
    this.Cursor = Cursors.Default;
}

Better, but that’s a lot of wrapping around a simple operation. Notice, that the try-finally is exactly the pattern that using is. Why not wrap this functionality into a simple to use class that handles the cursor reset automatically?

internal class WaitCursor : IDisposable
{
    private Control _control = null;
    public WaitCursor(Control control)
    {
        _control = control;
        _control.Cursor = Cursors.WaitCursor;
    }
    public void Dispose()
    {
        _control.Cursor = Cursors.Default;
    }
}

And to use it in a form is simple:

using (new WaitCursor(this))
{
    //do work
}

Of course, you could easily add functionality like restoring the previous cursor instead of always the default, handling exceptions, make it thread-aware so it uses Invoke if necessary, better error-handling, etc.

Technorati Tags: ,,,