永远不会激活显示窗口

时间:2017-09-22 16:39:22

标签: c# wpf

我试图从非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之后归档窗口被激活?

1 个答案:

答案 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)
            {
            }
        });
    }
});