【问题标题】:WPF Cross-Thread MessageBox not blocking main thread inputWPF跨线程消息框不阻塞主线程输入
【发布时间】:2016-01-22 15:25:24
【问题描述】:

我正在尝试使用 Dispatcher.Invoke 显示来自另一个 ThreadMessageBox

MessageBox 确实出现了。但是不点击MessageBox上的OK按钮,我仍然可以控制主窗口。

我在想是否有办法在单击OK 按钮之前阻止主窗口输入?

感谢任何帮助。

到目前为止我的代码:

void ShowError(String message)  //I call this function in another thread
{
    if (this.Dispatcher.CheckAccess())
        MessageBox.Show(message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
    else
    {
        this.Dispatcher.Invoke(
            new Action(() =>
            {
                MessageBox.Show(message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }));
    }
}

【问题讨论】:

  • 您是否从调用 ShowError 的代码或包含 ShowError 的类中引用了窗口?
  • 是的,让我试试你的解决方案。 :)

标签: c# wpf multithreading


【解决方案1】:

保证消息框阻塞窗口的唯一方法是将窗口传递给消息框。

void ShowError(String message, Window windowToBlock)  //I call this function in another thread
{
    if (this.Dispatcher.CheckAccess())
        MessageBox.Show(windowToBlock, message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
    else
    {
        this.Dispatcher.Invoke(
            new Action(() =>
            {
                MessageBox.Show(windowToBlock, message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }));
    }
}

【讨论】:

  • 谢谢你,这行得通!我不知道MessageBox.Show 方法有owner 参数。
猜你喜欢
  • 2018-02-16
  • 1970-01-01
  • 1970-01-01
  • 2016-09-25
  • 1970-01-01
  • 1970-01-01
  • 2015-12-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多