It is common for a developer to display a hour glass while their application is running a long operation. When running an application in Windows Vista the cursors typically look like this:
The Wait Cursor
The Default Cursor
In order to toggle the cursors, I typically will write a block of code that looks something like this:
1: this.Cursor = Cursors.WaitCursor;
2: try {
3: //Start long operation
4: }
5: finally {
6: //use the finally block to guarantee that the cursor returns to normal
7: this.Cursor = Cursors.Default
8: }
To my surprise, this is not always the right technique. The problem with this approach is that it temporarily sets the WaitCursor, but does not guarantee that the WaitCursor will remain until the end of your operation. Why? Because other operations within your program can easily reset the cursor back to the Default cursor. Having the cursor flip back and forth is not only distracting but it also has the potential to make the user think that the operation has completed when in fact it is still running. So how do we avoid this? Well one way is the use the Form's UseWaitCursor property instead. Here is an example
1: this.UseWaitCursor = true;
2: try {
3: //Start long operation
4: }
5: finally {
6: //use the finally block to guarantee that the cursor returns to normal
7: this.UseWaitCursor = false;
8: }
This method will display the WaitCursor for the specified form (referenced by the keyword this in the snippet above) or control and all its child controls until you set the UseWaitCursor back to false. If you have the situation where your operation blocks input not just to a single window but your entire application that you can use the Application.UseWaitCursor static property:
1: Application.UseWaitCursor = true;
2: try {
3: //Start long operation
4: }
5: finally {
6: //use the finally block to guarantee that the cursor returns to normal
7: Application.UseWaitCursor = false;
8: }
By using the Application's UseWaitCursor property you will override any changes made to the cursor by a control of form. Therefore, guaranteeing that you have the right cursor displayed to the end user. Hopefully the next time you set the WaitCursor in your application you will remember these tips. After all, at the end of the day, user experience is the only thing that really matters.