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
How to decompile Java code with JetBrains IntelliJ IDEA (2018.2.3, Windows 10)October 5, 2018
Java Programming Tip: SWT Photo Frame ProgramOctober 31, 2016
Vault 3 (Desktop) Version 1.63 ReleasedSeptember 9, 2016
"Compliance with Court Orders Act of 2016"April 9, 2016
Disable "Visual Voicemail" on Android / T-MobileJanuary 17, 2016
IPv6 HumorDecember 10, 2015
Java Programming Tip: Specify the JVM time zoneDecember 7, 2015