Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

WaitCursor hack using using

0.00/5 (No votes)
2 Mar 2004 1  
A simple way to display a WaitCursor.

Introduction

A hack to replicate MFC's CWaitCursor class in C#.

Background

I found that the using keyword in C# has two uses:

  1. The using directive, which we all know.
  2. The using statement, which is v. cool. This gave me the idea for this article.

Using the code

Basically, the using statement declares that for a variable, Dispose is always called at the end of the statement block.

This is a good thing. By writing a class that implements IDispose, we can have destructor-like semantics that allow us to clean up after ourselves. This is useful in many scenarios; this article describes one such use.

We will start with our requirements. We want to be able to write code like this:

    using ( new CWaitCursor() )
    {
        // Do something interesting

    }

Just to make things a bit more interesting, we will start by writing a class that displays any System.Windows.Forms.Cursor. It saves the current cursor, displays the specified cursor, then in the Dispose method, it switches back to the saved cursor. This is really quite simple, and looks something like this:

using System.Windows.Forms;

namespace Common
{
    internal class CCursor : IDisposable
    {
        private Cursor saved = null;

        public CCursor( Cursor newCursor )
        {
            saved = Cursor.Current;

            Cursor.Current = newCursor;
        }

        public void Dispose()
        {
            Cursor.Current = saved;
        }
    }
}

Our CWaitCursor class just derives from this code, specifying the Cursors.WaitCursor:

    internal class CWaitCursor : CCursor
    {
        public CWaitCursor() : base( Cursors.WaitCursor ) {}
    }

And we're done! The cursor is guaranteed to be cleaned up however we exit the using statement.

Points of Interest

The using statement is good; it should be used everywhere (IMHO) because it gives us some control over disposal of our objects.

I use it a lot in GDI stuff. For example:

    using ( Brush brush = new SolidBrush( colour ) )
        Graphics.FillRectangle( brush, rect );

History

Version 1: 2004 March 3.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here