我试图从非UI线程中显示一个窗口:
Dispatcher dispatcher =
Application.Current != null
? Application.Current.Dispatcher
: Dispatcher.CurrentDispatcher;
if (!dispatcher.CheckAccess())
{
dispatcher.Invoke(() =>
{
TestWindow window = new TestWindow();
window.Topmost = true;
if (window.ShowDialog() == true)
{
}
});
}
我的问题是窗口确实在顶部但未激活。 有必要点击它获得逻辑焦点的窗口。
如何在ShowDialog之后归档窗口被激活?
答案 0 :(得分:2)
应该激活它。尝试处理Activated
事件。或者处理Loaded
事件并将控件聚焦在dalog窗口中。
这样做有效,即TextBox
无需任何点击即可重点关注:
Task.Run(()=>
{
Dispatcher dispatcher = Application.Current != null ?
Application.Current.Dispatcher : Dispatcher.CurrentDispatcher;
if (!dispatcher.CheckAccess())
{
dispatcher.Invoke(() =>
{
TextBox tb = new TextBox();
Window window = new Window() { Content = tb };
window.Activated += (ss, ee) => { /* ... */ };
window.Loaded += (ss, ee) => tb.Focus();
window.Topmost = true;
if (window.ShowDialog() == true)
{
}
});
}
});