Images in this post missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at imagehelp@codebetter.com

Howto: Manage Cursor Changing for WinForms Applications

As a long time WinForms developer I always have had the need
to swap out the current cursor (mouse pointer, not some database cursor) for
another cursor, normally the ‘wait’ cursor, while performing some task after
things such as a button click.

In the past I have used some pretty straight forward code
that solved this problem easily, but was a pain to replicate because of the
number of lines of code.The good news was
that when .Net 2.0 came out and they included the ‘using’ keyword in VB.net I found
a much simpler and elegant solution to my problem.

Here is the way that I once swapped out cursors:

// Grab the current, entry cursor

// Set the current cursor to the wait and continue

Cursor currentCursor = Cursor.Current;

Cursor.Current = Cursors.WaitCursor;

try

{

// Do something here

}

finally

{

// Swap the current cursor back to the original cursor

Cursor.Current = currentCursor;

}

Here is the new 'more elegant' way by using the 'using' keyword:

using ( newCursorKeeper( Cursors.WaitCursor ) )

{

// Do something here

}

As you can see, by using the 'using' keyword I have reduced the number of lines needed to be repeated to only a few.

Now, lets take a look at the code in the CursorKeeper class to see how this works behind the scenes.

publicclassCursorKeeper : IDisposable

{

privateCursor _originalCursor;

privatebool _isDisposed = false;

public CursorKeeper( Cursor newCursor )

{

_originalCursor = Cursor.Current;

Cursor.Current = newCursor;

}

#region " IDisposable Support "

protectedvirtualvoid Dispose( bool disposing )

{

if ( !_isDisposed )

{

if ( disposing )

{

Cursor.Current = _originalCursor;

}

}

_isDisposed = true;

}

publicvoid Dispose()

{

// Do not change this code. Put cleanup code in Dispose(ByVal disposing As Boolean) above.

Dispose( true );

GC.SuppressFinalize( this );

}

#endregion

}

Well, any I thought I would share how we manage the cursor changes with everyone. If someone else has another way to handle this, let me.