c# - MessageBox.Show 导致无法拾取光标的变化

标签 c# wpf

我有一个标准的 WPF MainWindow 类,我想要的是使用 System.Windows.MessageBox 显示一个消息框,得到用户的响应,然后运行一个长运行操作(下面通过调用 Sleep(...) 进行模拟)。我想在操作前将光标设置为Cursors.Wait,并在结束时恢复正常。这是我得到的:

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;
            }));
    }
}

这不起作用:光标永远不会作为等待光标出现。但是,如果我注释掉 MessageBox 行,它确实有效。这是怎么回事,我怎样才能让它按预期工作?

最佳答案

以下代码对我有用:而不是

Cursor = Cursors.Wait;

试试这个:

Mouse.OverrideCursor = Cursors.Wait;
Mouse.UpdateCursor();

您以相反的方式关闭等待光标:

Mouse.OverrideCursor = null;
Mouse.UpdateCursor();

关于c# - MessageBox.Show 导致无法拾取光标的变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13933232/

相关文章:

.net - 使用 ElementHost 在 Winform 应用程序中托管 WPF UserControl 有什么缺点吗?

c# - 在 WPF 中使用 MVVM 模式在运行时加载 XAML

c# - 将 Ruby 的时间转换为 C#

c# - 从 asp.net 背后的代码显示字符串的最简单方法

c# - WPF 动画不适用于 "fast"属性更改

c# - 3D 图形 - 矩阵数学不起作用

wpf - 您有 AttachedPropertyBrowsableWhenAttributePresentAttribute 用法的真实示例吗?

c# - 如何在wpf中使用 TreeView 项目访问 TreeView 项目?

c# - 双倍值变化引起的火灾事件

c# - 在客户端运行时更新 Silverlight 应用程序