Preserving the cursor when putting up an hour glass - Win32 best practice in a .NET world

Today's quickie tip comes from the world of Win32 best practice. 

In Win32, we were taught to return resources to the state they were before we were using them.  This is good OO programming practice generally (makes your operations more encapsulated).  My specific example here is the best way to put up an hourglass cursor to the user for a lengthy op.

void Save()
{
    // save the old cursor...
    Cursor oldCursor = this.Cursor;
    // put up an hourglass...
    this.Cursor = Cursors.WaitCursor;
    try
    {
        // do some work...
    }
    finally
    {
        // restore the old cursor....
        this.Cursor = oldCursor;
    }
}

The idea behind this apporach is that you remove the assumption that the cursor was a default cursor before you got into this method.  The bad way of doing this is to explictly set the cursor back to what you think it was before you got into the method.  This may not be the case as another method may have changed the cursor before you get your chance to run.  In effect, you would have messed up the state of the object and broken the operation of the up-level method.

Moral: always return state back to how it was before you changed it, rather than what you think it was.

2 Comments

  • How many times have we seen the cursor set back to the hourglass?!

    Thanks for the reminder, I think it's much needed!

  • How about a helper class like this (I dont know how it'll look - no preview...):



    class TempWaitCursor : IDisposable

    {

    Control target;

    Cursor oldCursor;



    public TempWaitCursor(Control target)

    {

    this.target = target;

    oldCursor = target.Cursor;

    target.Cursor = Cursors.WaitCursor;

    }



    public void Dispose()

    {

    target.Cursor = oldCursor;

    }

    }



    Usage:



    void Save()

    {

    using (new TempWaitCursor(this))

    {

    // do some work...

    }

    }





Comments have been disabled for this content.