Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF App loses focus completely on window close

Tags:

.net

wpf

What most likely happened here is you have two independent top level windows and closed one of them. This will sometimes cause focus to jump to another application.

This also happens if one windows owns a second, which in turn owns a third. Probable BUG in the Win32 API but its been with us forever so good luck getting it fixed.

The workaround is to manually hand focus back to child in the Closing event of the grandchild. But in this case, grandchild is a messagebox so you can't do that. The easiest thing to do is to own messagebox to parent. The next easiest is to make your own messagebox control.


This is a very annoying bug, the most common solution provided is:

call Me.Owner.Focus in the Window_Unloaded or Window_Closing event.

But that still doesnt work 100%, you still see the background-window flashing to the foreground (very briefly), before focus is restored correctly.

I found a method which works better:

call Me.Owner.Activate before Me.Close (or in the _Closing event).


Maybe i am quite late on the matter.
@HCL this problem could be resolved more easily by setting the options parameter of the MessageBox.show() to MessageBoxOptions.None.

Cheers...


2020 and still in trouble...

Workaround for Wpf :

    public ContactsWindow()
    {
        InitializeComponent();

        Closing += ContactsWindow_Closing;
    }

    private void ContactsWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
    {
        Owner?.Activate();
    }

It seems to work for me, interested in any news