创建另一个线程来获取当前窗口(System.Windows.Application.Current.MainWindow

本文关键字:System Windows Application MainWindow Current 窗口 线程 另一个 获取 创建 | 更新日期: 2023-09-27 18:06:59

我需要当前窗口显示自定义MessageBox。我这样做:

Window owner = System.Windows.Application.Current.MainWindow;

有时是有效的。当它不工作时,我得到这个错误:

System.InvalidOperationException: {"The calling thread cannot access this object because a different thread owns it."}
InnerException: null
Message: The calling thread cannot access this object because a different thread owns it.

一个解决方案是将这个调用踢到一个单独的线程而不是主线程?如果有,我该怎么做?谢谢。

创建另一个线程来获取当前窗口(System.Windows.Application.Current.MainWindow

您需要使用Dispatcher和Invoke/BeginInvoke将调用封送回UI线程:

System.Windows.Application.Current.Dispatcher.Invoke((Action)() =>
{
       Window owner = System.Windows.Application.Current.MainWindow;
       // Use owner here - it must be used on the UI thread as well..
       ShowMyWindow(owner);
});

Reed Copsey的回答:

System.Windows.Application.Current.Dispatcher.Invoke((Action)delegate
{
       Window owner = System.Windows.Application.Current.MainWindow;
       // Use owner here - it must be used on the UI thread as well..
       ShowMyWindow(owner);
});