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

后端 未结 3 1039
粉色の甜心
粉色の甜心 2020-12-30 03:03

In my WPF app, I sometimes being up a System.Windows.MessageBox. When it is initially displayed, it is shown on top of my main application window, as I would li

3条回答
  •  借酒劲吻你
    2020-12-30 03:41

    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).

提交回复
热议问题