Vishful thinking…

Cursor change helper

Posted in Uncategorized by viswaug on September 28, 2007

I created a little cursor helper today to make it easy to change the cursor in a windows forms app. When a button click event in a form triggers a long operation, you would want to convey a visual feedback that the operation is in process and that the operation is complete by changing the cursor to a Wait cursor and back. If your code to do the above looks like this, 

Cursor c = this.Cursor;

this.Cursor = Cursors.WaitCursor;

//Do long operation

System.Threading.Thread.Sleep(3000);

this.Cursor = c;

DownArrow

then you can save some pain in your wrist by using the CursorHelper class and your code can look like this.

using (new CursorHelper(Cursors.WaitCursor))

{

     //Do long operation

     System.Threading.Thread.Sleep(3000);

}

Here is the CursorHelper utility class.

    public class CursorHelper:IDisposable

    {

        Cursor _oldCursor;

        Cursor _newCursor;

 

        public CursorHelper(Cursor pnewCursor)

        {

            _oldCursor = Cursor.Current;

            _newCursor = pnewCursor;

            Cursor.Current = _newCursor;

        }

 

        #region IDisposable Members

 

        public void Dispose()

        {

            Cursor.Current = _oldCursor;

        }

 

        #endregion

    }