posted on Saturday, October 02, 2004 1:55 PM
by
taylorza
CWaitCursor for .NET
Being mostly a middle tier type I have not done much front end UI stuff for quite sometime. But lately I have been doing some Windows Forms development and I have been making extensive use of the following piece of code that I developed years ago.
class CursorManager : IDisposable
{
private bool _disposed = false;
private Control _owner;
private Cursor _prevCursor;
public CursorManager(Cursor cursor) : this(null, cursor)
{
}
public CursorManager(Control owner, Cursor cursor)
{
_owner = owner;
if ( _owner != null )
{
_prevCursor = _owner.Cursor;
_owner.Cursor = cursor;
}
else
{
_prevCursor = Cursor.Current;
Cursor.Current = cursor;
}
}
~CursorManager()
{
Dispose();
}
public void Dispose()
{
if (!_disposed)
{
if ( _owner != null )
_owner.Cursor = _prevCursor;
else
Cursor.Current = _prevCursor;
_disposed = true;
}
GC.SuppressFinalize(
this);
}
}
as elegant as the C++ solution. The C# using statement brings some elegance to this technique, while the current VB.NET syntax is not quite so sleek the VB.NET 2.0 will provide the same elegance as the C# syntax.
C#
using
(new CursorManager(this, Cursors.WaitCursor))
{
DoLongOperation();
}
VB.NET
Dim waitCursor As CursorManager
Try
waitCursor = New CursorManager(Me, Cursors.WaitCursor)
DoLongOperation()
Finally
If Not waitCursor Is Nothing Then waitCursor.Dispose()
End Try