Action Heinz
Action Heinz

Reputation: 744

Showing a window is never activated

I'm trying to show a window from a non UI thread:

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

My problem is that the window is indeed on top but not activated. It is necessary to click on the window that it gets the logical focus.

How can I archive that the window is activated after ShowDialog?

Upvotes: 1

Views: 41

Answers (1)

mm8
mm8

Reputation: 169270

It should be activated. Try to handle the Activated event. Or handle the Loaded event and focus a control in the dalog window.

This works, i.e. the TextBox is focused without any click:

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

Upvotes: 2

Related Questions