ninja star Things I Bet You Didn't Know About Using The WaitCursor

by Michael Ceranski, posted on May 21 2009

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.

Tags: ,
blog comments powered by Disqus

About the author

MikeMichael Ceranski is a developer specializing in the .NET stack. I have spent time as a DBA, Web Developer and even a network engineer. Up til now most of my career has revolved around the .NET stack but I have recently taken an interest in microcontrollers which has forced me to get acquainted with lower level languages such as C, and C++.

View my resume

Sponsors