views:

609

answers:

3

I have a C# application that has users login to it, and because the hashing algorithm is expensive, it takes a little while to do. How can I display the Wait/Busy Cursor (usually the hourglass) to the user to let them know the program is doing something?

The project is in C#.

+9  A: 

You can use Cursor.Current.

// Set cursor as hourglass
Cursor.Current = Cursors.WaitCursor;

// Execute your time-intensive hashing code here...

// Set cursor as default arrow
Cursor.Current = Cursors.Default;

However, if the hashing operation is really lengthy (MSDN defines this as more than 2-7 seconds), you should probably use a visual feedback indicator other than the cursor to notify the user of the progress. For a more in-depth set of guidelines, see this article.

Edit:
As @Am pointed out, you may need to call Application.DoEvents() after Cursor.Current = Cursors.WaitCursor; to ensure that the hourglass is actually displayed.

Donut
this won't necessary change the cursor - if the message loop won't be called during the time-intensive code. to enable it you need to add _Application.DoEvents();_ after the first cursor set.
Am
+1 for link to article - good stuff!
JeffH
You probably want a try..finally block after setting Current, too (insuring that Current gets reset to Default).
TrueWill
+1  A: 

My approach would be to make all the calculations in a background worker.

Then change the cursor like this:

this.Cursor = Cursors.WaitCursor;

And in the thread's finish event restore the cursor:

this.Cursor = Cursors.Default;

Note, this can also be done for specific controls, so the cursor will be the hourglass only when the mouse is above them.

Am
They are done in a background thread...
Malfist
@Malfist: good approach :), then all you need to do is place the restore in the end event, and your done.
Am
+1  A: 

Actually,

Cursor.Current = Cursors.WaitCursor;

temporarily sets the Wait cursor, but doesn’t ensure that the Wait cursor shows until the end of your operation. Other programs or controls within your program can easily reset the cursor back to the default arrow as in fact happens when you move mouse while operation is still running.

A much better way to show the Wait cursor is to set the UseWaitCursor property in a form to true:

form.UseWaitCursor = true;

This will display wait cursor for all controls on the form until you set this property to false. If you want wait cursor to be shown on Application level you should use:

Application.UseWaitCursor = true;
draganstankovic