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 ( new CursorKeeper( 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.
public class CursorKeeper : IDisposable
{
private Cursor _originalCursor;
private bool _isDisposed = false;
public CursorKeeper( Cursor newCursor )
{
_originalCursor = Cursor.Current;
Cursor.Current = newCursor;
}
#region " IDisposable Support "
protected virtual void Dispose( bool disposing )
{
if ( !_isDisposed )
{
if ( disposing )
{
Cursor.Current = _originalCursor;
}
}
_isDisposed = true;
}
public void 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.
Thanks and happy developing..... DW
Posted
10-06-2006 6:26 AM
by
Derik Whittaker