簡體   English   中英

如何顯示另一個UI線程上的對話框

[英]How can I show dialog on UI thread from another

我在多個線程上使用Show.Dialog,但是有問題。 當關閉從UI線程調用的對話框時,即使仍存在從另一個線程調用的某些對話框,也會激活MainWindow。 為了避免這種情況,我想在另一個UI線程上顯示對話框,但是怎么可能呢? 還是我有其他方法可以避免此問題?

public partial class CustomMsgBox : Window
{
    //this class implements a method that automatically
    //closes the window of CustomMsgBox after the designated time collapsed

    public CustomMsgBox(string message)
    {
        InitializeComponent();
        Owner = Application.Current.MainWindow;
        //several necessary operations...
    }

    public static void Show(string message)
    {
        var customMsgBox = new CustomMsgBox(message);
        customMsgBox.ShowDialog();
    }
}

public class MessageDisplay
{
    //on UI thread
    public delegate void MsgEventHandler(string message);
    private event MsgEventHandler MsgEvent = message => CustomMsgBox.Show(message);

    private void showMsg()
    {
        string message = "some message"
        Dispatcher.Invoke(MsgEvent, new object[] { message });
    }
}

public class ErrorMonitor
{
    //on another thread (monitoring errors)
    public delegate void ErrorEventHandler(string error);
    private event ErrorEventHandler ErrorEvent = error => CustomMsgBox.Show(error);
    private List<string> _errorsList = new List<string>();

    private void showErrorMsg()
    {
        foreach (var error in _errorsList)
        {
            Application.Current.Dispatcher.BeginInvoke(ErrorEvent, new object[] { error });
        }
    }
}

當從UI線程調用的CustomMsgBox自動關閉時,即使仍然有一些從監視線程調用的CustomMsgBoxes,也會激活MainWindow。

您只應從UI線程打開對話框。 您可以使用調度程序調用UI-Thread:

// call this instead of showing the dialog direct int the thread
this.Dispatcher.Invoke((Action)delegate()
{
    // Here you can show your dialiog
});

您可以簡單地編寫自己的ShowDialog / Show方法,然后調用調度程序。

希望我理解您的問題正確。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM