WPF跨线程MessageBox不阻塞主线程输入

时间:2021-09-20 02:26:46

I'm trying to show a MessageBox from another Thread using Dispatcher.Invoke.

我正在尝试使用Dispatcher.Invoke从另一个线程显示MessageBox。

The MessageBox did show up. But without clicking the OK button on the MessageBox, I can still control the main window.

MessageBox确实出现了。但是,如果没有单击MessageBox上的OK按钮,我仍然可以控制主窗口。

I'm thinking if there's a way to block the main window input before clicking the OK button?

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

Any help is appreciated.

任何帮助表示赞赏。

Code I have so far:

我到目前为止的代码:

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

1 个解决方案

#1


7  

The only way to be guaranteed that the message box blocks the window is by passing the window in to the message box.

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

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

#1


7  

The only way to be guaranteed that the message box blocks the window is by passing the window in to the message box.

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

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