C# Cursor Handler

Back in my days of Delphi Windows application development, I often had need to change the cursor to an hourglass as my highly inefficient code took an age to execute. Initially I did this by storing the current cursor, changing to an hourglass and finally changing back to the original cursor, wrapped in a try..finally block to ensure the cursor did get changed back even when my code blew up in the interim.

Then I went to a presentation by Malcolm Groves who explained how to do this in a much neater way using Delphi's interface support. I particularly liked this technique because it saved lines of code (I'm essentially lazy) and it was also a slightly perverse way to use interfaces.

So moving to C#, I thought for a while that I'd be back to those long-winded try..finally blocks, but then I realised C# has a way of sneakily adding try..finally blocks for you. By writing a class that implemented IDisposable, I was able to do the same thing as I'd been shown how to do in Delphi. Again it saves lines of code and is also a slightly perverse use of a language feature. So here's the code. To use it, just do the following

using (new CursorHandler()) { //some longwinded operation }

Er, and that's it... Enjoy!

using System;
using System.Windows.Forms;

namespace Utils
{
  public class CursorHandler : IDisposable
  {
    Cursor savedCursor;
    public CursorHandler()
    {
      savedCursor = Cursor.Current;
      Cursor.Current = Cursors.WaitCursor;
    }

    ~CursorHandler()
    {
      Restore();
    }

    public void Dispose()
    {
      Restore();
      GC.SuppressFinalize(this);
    }

    private void Restore()
    {
      Cursor.Current = savedCursor;
    }
  }
}