I've got a standard WPF MainWindow class, and what I'd like is to show a message box using System.Windows.MessageBox
, get a response from the user and then run a long running operation (simulated below by a call to Sleep(...)
). I'd like to set the cursor to Cursors.Wait
before the operation, and back to normal at the end. Here's what I've got:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void ui_button_Click(object sender, RoutedEventArgs e)
{
if (MessageBox.Show("Do you want to change the background?", "Change background", MessageBoxButton.YesNo) == MessageBoxResult.No)
{
return;
}
Cursor = Cursors.Wait;
Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(() =>
{
System.Threading.Thread.Sleep(1500);
if (Background != Brushes.Green)
{
Background = Brushes.Green;
}
else
{
Background = Brushes.White;
}
Cursor = Cursors.Arrow;
}));
}
}
This doesn't work: the cursor never appears as the wait cursor. However, if I comment out the MessageBox
lines, it does work. What's going on here, and how can I get it to work as intended?
The following code works for me: instead of
Cursor = Cursors.Wait;
try this:
Mouse.OverrideCursor = Cursors.Wait;
Mouse.UpdateCursor();
You turn off the wait cursor the opposite way:
Mouse.OverrideCursor = null;
Mouse.UpdateCursor();
You run background change in the same UI thread as cursor change. Sure it`s busy with Sleep so it doesn`t show cursor change. Just make example as it should be (with several threads) and everything will be fine!
private void ui_button_Click(object sender, RoutedEventArgs e)
{
if (MessageBox.Show("Do you want to change the background?", "Change background", MessageBoxButton.YesNo) == MessageBoxResult.No)
{
return;
}
Cursor = Cursors.Wait;
BackgroundWorker bw = new BackgroundWorker();
bw.DoWork += BwOnDoWork;
bw.RunWorkerCompleted += BwOnRunWorkerCompleted;
bw.RunWorkerAsync();
}
private void BwOnRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs runWorkerCompletedEventArgs)
{
if (Background != Brushes.Green)
{
Background = Brushes.Green;
}
else
{
Background = Brushes.White;
}
Cursor = Cursors.Arrow;
}
private void BwOnDoWork(object sender, DoWorkEventArgs doWorkEventArgs)
{
System.Threading.Thread.Sleep(1500);
}
try
DialogResult dialogResult = MessageBox.Show("Do you want to change the background?", "Change background", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.No)
{
return;
}
instead of
if (MessageBox.Show("Do you want to change the background?", "Change background", MessageBoxButton.YesNo) == MessageBoxResult.No)
Try putting your code that you want to run in other thread
ThreadPool.QueueUserWorkItem(delegate
{
//your code here...
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.