Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF Cross-Thread MessageBox not blocking main thread input

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

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

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

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);
            }));
    }
}
like image 592
J3soon Avatar asked Jan 22 '16 15:01

J3soon


1 Answers

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);
            }));
    }
}
like image 171
Scott Chamberlain Avatar answered Sep 21 '22 16:09

Scott Chamberlain