Eric Bergman-Terrell's Blog

.NET Programming Tip: How to Display a Busy Cursor While Loading a WPF TextBox with a Large Amount of Text
June 13, 2010

My File Search application displays found files in a DataGrid. When the user clicks on a file, the file's entire text is loaded into a TextBox below the DataGrid:

File Search - Found Files

If the file is large, loading the text can take a long time, so it's appropriate to display a busy cursor while the TextBox is loading. I tried the following code and was puzzled to find that it didn't work (the TextBox is named "FileContents"). I never saw the wait cursor, even when loading the text took several seconds.

...
Cursor = System.Windows.Input.Cursors.Wait;
FileContents.Text = File.ReadAllText(fileInfo.FullName);
Cursor = System.Windows.Input.Cursors.Arrow;
...

The problem is that the assignment of the TextBox's propery does not block. It must be processed by a background thread. My solution was to write a method to change the cursor to the Arrow cursor, and queue that method to run after the TextBox's text was updated:

FileContents.Dispatcher.BeginInvoke(DispatcherPriority.Background, new DispatcherOperationCallback(SetCursorToArrow), null);

Here's the complete source code snippet:

try
{
  Cursor = System.Windows.Input.Cursors.Wait;
  FileContents.Text = File.ReadAllText(fileInfo.FullName);
}
catch (Exception ex)
{
  FileContents.Text = string.Empty;
  System.Windows.MessageBox.Show(ex.Message, Globals.ProgramName, MessageBoxButton.OK, MessageBoxImage.Error);
}
finally
{
  // Queue a request to set the cursor back to the arrow cursor. Reason: The changed text is loaded into the textbox
  // asynchronously, and the TextChanged event is fired before the text change is visible to the user.
  FileContents.Dispatcher.BeginInvoke(DispatcherPriority.Background, new DispatcherOperationCallback(SetCursorToArrow), null);
}

...

private object SetCursorToArrow(object obj)
{
  Cursor = System.Windows.Input.Cursors.Arrow;
  return null;
}
Keywords: .NET, WPF, Busy Cursor, TextBox, Background Thread, Thread

Reader Comments

Comment on this Blog Post

Recent Posts

TitleDate
.NET Public-Key (Asymmetric) Cryptography DemoJuly 20, 2025
Raspberry Pi 3B+ Photo FrameJune 17, 2025
EBTCalc (Android) Version 1.53 is now availableMay 19, 2024
Vault 3 Security EnhancementsOctober 24, 2023
Vault 3 is now available for Apple OSX M2 Mac Computers!September 18, 2023
Vault (for Desktop) Version 0.77 ReleasedMarch 26, 2023
EBTCalc (Android) Version 1.44 is now availableOctober 12, 2021