Wednesday, October 3, 2012

Change Cursor to Wait Cursor



This example demonstrates how to show Wait Cursor in C# for any lengthy operation.

Mouse cursor displayed over any control in windows forms application is determined by Control.Cursor property. If you want to change the mouse cursor at application level use static property Current of Cursor class. To show hourglass cursor assign value Cursors.WaitCur­sor. To return back the default behavior (to display control specific cursor) assign back value Cursors.Default to the Cursor.Current property. See example below.


Cursor.Current = Cursors.WaitCursor;
 // Your operations!  
Cursor.Current = Cursors.Default;

How does it work at windows level:

Windows sends the window that contains the mouse cursor the WM_SETCURSOR message, giving it an opportunity to change the cursor shape. A control like TextBox takes advantage of that, changing the cursor into a I-bar. The Control.Cursor property determines what shape will be used.

The Current.Cursor property changes the shape directly, without waiting for a WM_SETCURSOR response. In most cases, that shape is unlikely to survive for long. As soon as the user moves the mouse, WM_SETCURSOR changes it back to Control.Cursor.

The UseWaitCursor property was added in .NET 2.0 to make it easier to display an hourglass. Unfortunately, it doesn't work very well. It requires a WM_SETCURSOR message to change the shape and that won't happen when you set the property to true and then do something that takes a while.