How can I display the Wait/Busy Cursor (usually the hourglass) to the user to let them know the program is doing something?
13 Answers
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.
-
26this 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.– AmirshkCommented Oct 14, 2009 at 19:54
-
17You probably want a try..finally block after setting Current, too (insuring that Current gets reset to Default).– TrueWillCommented Dec 23, 2009 at 17:50
-
8FYI, i couldnt get the above to work, but by changing it to this.cursor = cursors.waitcursor; it worked. Commented Jul 1, 2012 at 16:01
-
4Hourglass was not displayed if I used Application.DoEvents() after Cursor.Current = Cursors.WaitCursor However, it did worked without Application.DoEvents() . Not sure Why– VbpCommented Nov 5, 2013 at 13:58
-
19It is better to use
Application.UseWaitCursor = true
andApplication.UseWaitCursor = false
Commented Aug 24, 2016 at 17:45
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;
-
Good to know. I was trying to do the same in WPF, and ended up with Cursor = Cursors.Wait and Cursor = Cursors.Arrow. But I couldn't find the Cursor under App– itshoCommented Jul 28, 2013 at 11:02
-
3
-
2I found that, when setting form.UseWaitCursor = false at the end of the operation, it doesn't actually reset the cursor until you move or click the mouse. OTOH, form.Cursor doesn't have this problem. I couldn't get Cursor.Current to work at all.– StewartCommented Aug 25, 2017 at 15:20
-
Definitely use this if you want to use the wait cursor. I tried
Cursor.Current
but it kept being reset instantly for some reason, this solution makes the waiting cursor persist until changed tofalse
. Commented Mar 27, 2021 at 16:44
Building on the previous, my preferred approach (since this is a frequently performed action) is to wrap the wait cursor code in an IDisposable helper class so it can be used with using() (one line of code), take optional parameters, run the code within, then clean up (restore cursor) afterwards.
public class CursorWait : IDisposable
{
public CursorWait(bool appStarting = false, bool applicationCursor = false)
{
// Wait
Cursor.Current = appStarting ? Cursors.AppStarting : Cursors.WaitCursor;
if (applicationCursor) Application.UseWaitCursor = true;
}
public void Dispose()
{
// Reset
Cursor.Current = Cursors.Default;
Application.UseWaitCursor = false;
}
}
Usage:
using (new CursorWait())
{
// Perform some code that shows cursor
}
-
Inspired by: codeproject.com/Articles/6287/WaitCursor-hack-using-using– tornoCommented Sep 23, 2015 at 13:27
-
1Hadn't seen that, but yes similar approach. He backs up the current cursor then restores it, which may be useful if you're doing heavy cursor changing.– mhappsCommented Sep 26, 2015 at 13:34
It is easier to use UseWaitCursor at the Form or Window level. A typical use case can look like below:
private void button1_Click(object sender, EventArgs e)
{
try
{
this.Enabled = false;//optional, better target a panel or specific controls
this.UseWaitCursor = true;//from the Form/Window instance
Application.DoEvents();//messages pumped to update controls
//execute a lengthy blocking operation here,
//bla bla ....
}
finally
{
this.Enabled = true;//optional
this.UseWaitCursor = false;
}
}
For a better UI experience you should use Asynchrony from a different thread.
-
2This should be the ACCEPTED answer. It is the only one that uses try-finally. Commented May 20, 2015 at 15:20
-
1have my upvote, I was missing a try-finally in my implementation– JackCommented May 22, 2016 at 4:21
My approach would be to make all the calculations in a background worker.
Then change the cursor like this:
this.Cursor = Cursors.Wait;
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.
-
@Malfist: good approach :), then all you need to do is place the restore in the end event, and your done.– AmirshkCommented Oct 14, 2009 at 20:09
-
This is the clean solution if we need a responsive UI as well as inform something is running.– Sid133Commented Jul 30, 2021 at 8:13
-
But what do you do if your 2 sec task is loading data into the control itself? (such as RichTextbox) I don't think using a background worker would help in this case, but I could be wrong. Commented Mar 8, 2022 at 18:31
For Windows Forms applications an optional disabling of a UI-Control can be very useful. So my suggestion looks like this:
public class AppWaitCursor : IDisposable
{
private readonly Control _eventControl;
public AppWaitCursor(object eventSender = null)
{
_eventControl = eventSender as Control;
if (_eventControl != null)
_eventControl.Enabled = false;
Application.UseWaitCursor = true;
Application.DoEvents();
}
public void Dispose()
{
if (_eventControl != null)
_eventControl.Enabled = true;
Cursor.Current = Cursors.Default;
Application.UseWaitCursor = false;
}
}
Usage:
private void UiControl_Click(object sender, EventArgs e)
{
using (new AppWaitCursor(sender))
{
LongRunningCall();
}
}
OK so I created a static async method. That disabled the control that launches the action and changes the application cursor. It runs the action as a task and waits for to finish. Control returns to the caller while it waits. So the application remains responsive, even while the busy icon spins.
async public static void LengthyOperation(Control control, Action action)
{
try
{
control.Enabled = false;
Application.UseWaitCursor = true;
Task doWork = new Task(() => action(), TaskCreationOptions.LongRunning);
Log.Info("Task Start");
doWork.Start();
Log.Info("Before Await");
await doWork;
Log.Info("After await");
}
finally
{
Log.Info("Finally");
Application.UseWaitCursor = false;
control.Enabled = true;
}
Here's the code form the main form
private void btnSleep_Click(object sender, EventArgs e)
{
var control = sender as Control;
if (control != null)
{
Log.Info("Launching lengthy operation...");
CursorWait.LengthyOperation(control, () => DummyAction());
Log.Info("...Lengthy operation launched.");
}
}
private void DummyAction()
{
try
{
var _log = NLog.LogManager.GetLogger("TmpLogger");
_log.Info("Action - Sleep");
TimeSpan sleep = new TimeSpan(0, 0, 16);
Thread.Sleep(sleep);
_log.Info("Action - Wakeup");
}
finally
{
}
}
I had to use a separate logger for the dummy action (I am using Nlog) and my main logger is writing to the UI (a rich text box). I wasn't able to get the busy cursor show only when over a particular container on the form (but I didn't try very hard.) All controls have a UseWaitCursor property, but it doesn't seem have any effect on the controls I tried (maybe because they weren't on top?)
Here's the main log, which shows things happening in the order we expect:
16:51:33.1064 Launching lengthy operation...
16:51:33.1215 Task Start
16:51:33.1215 Before Await
16:51:33.1215 ...Lengthy operation launched.
16:51:49.1276 After await
16:51:49.1537 Finally
Okey,Other people's view are very clear, but I would like to do some added, as follow:
Cursor tempCursor = Cursor.Current;
Cursor.Current = Cursors.WaitCursor;
//do Time-consuming Operations
Cursor.Current = tempCursor;
With the class below you can make the suggestion of Donut "exception safe".
using (new CursorHandler())
{
// Execute your time-intensive hashing code here...
}
the class CursorHandler
public class CursorHandler
: IDisposable
{
public CursorHandler(Cursor cursor = null)
{
_saved = Cursor.Current;
Cursor.Current = cursor ?? Cursors.WaitCursor;
}
public void Dispose()
{
if (_saved != null)
{
Cursor.Current = _saved;
_saved = null;
}
}
private Cursor _saved;
}
Use this with WPF:
Cursor = Cursors.Wait;
// Your Heavy work here
Cursor = Cursors.Arrow;
-
1I like your answer but I would suggest placing it in the context of a try / finally. I used Donut's accepted answer for years, but it does not work in code behind on a C# .NET Core 3.1 WPF application like your answer. With the ,NET Core, Microsoft has changed the interface and objects in regards to cursors. Commented Oct 7, 2020 at 14:17
You can use:
Mouse.OverrideCursor = Cursors.Wait;
&&
Mouse.OverrideCursor = Cursors.Arrow;
A simple ScopeGuard
is a nice helper:
public record ScopeGuard(Action Action) : IDisposable
{
public void Dispose()
{
Action.Invoke();
}
}
and then
Enabled = false;
Application.UseWaitCursor = true;
Application.DoEvents();
using ScopeGuard sg = new(() =>
{
Application.UseWaitCursor = false;
Enabled = true;
});
// logic goes here
What worked for me in a .Net Windows Application:
Cursor = Cursors.WaitCursor;
...
Cursor = Cursors.Default;
No need for Application.DoEvents();
.