Force MessageBox to be on top of application window in .net/WPF

☆樱花仙子☆ 提交于 2019-11-30 06:40:09

Use the version of MessageBox.Show that takes a Window "owner" and pass your window.

MessageBox.Show(Application.Current.MainWindow, "Im always on top - of the main window");

If your possibly not on the UI thread try:

string msg="Hello!";
if (Application.Current.Dispatcher.CheckAccess()) {
    MessageBox.Show(Application.Current.MainWindow, msg);
}
else {
    Application.Current.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(()=>{
        MessageBox.Show(Application.Current.MainWindow, msg);
    }));
}

You can:
1. Invoke to block your thread until MessageBox is dismissed OR
2. BeginInvoke in which case your thread code will continue to execute but UI thread will block on MessageBox until its dismissed).

This is a quick way of putting the Message Box on top of the application windows.

MessageBox.Show(this ,"Output text"));

Inside your "public partial class MainWindow : Window" place the following code. So the Invoke will run your code inside UI thread.

void ShowErrorMessage(ERROR err)
{
    this.Dispatcher.Invoke((Action)(() =>
    {
        MessageBox.Show(err.description, err.code.ToString(), MessageBoxButton.OK, MessageBoxImage.Error);
    }));
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!