Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent parent window from going into background after child is closed?

So, I've been running into a problem with many of my WPF applications where after closing children windows of a window, that window (usually my main window) will go into background, behind anything else I have open. After some research, I found this bug report submitted to Microsoft: Bug Report and their usual response of "The WPF team has recently reviewed this issue and will not be addressing it..."

Has anyone been successful at tackling this on their own? It drives me mad and I can't figure out a solution.

EDIT:

I gave some thought to what James had recommended in his answer and after almost dismissing his suggestion due to the inconvenient nature of the window being on top of everything else, I came up with this:

ChildWindow.Closed += delegate
{
    ChildWindow = null;
    this.Topmost = true;
    System.Threading.Thread.Sleep(1000);
    this.Topmost = false;
};

So, when child's Closed() event is raised, I make sure that the parent window is the topmost. Then, I let the thread sleep for 1 second and set topmost to false to allow other windows to overlay this parent window.

Reason for the pause: If I don't use a pause and just this.Topmost = true followed by this.Topmost = false, then the effect never takes place and the bug still occurs because of the timing for the bug.

I'm not sure if it's the best way, but it works. Microsoft needs to invest more resources into WPF.

like image 610
B.K. Avatar asked Feb 18 '14 05:02

B.K.


2 Answers

set the Main window to:

Topmost=true

This should help a little, but will not solve the issue entirely. Just keep in mind that if another application has the setting, they could end up on top of the application anyways. Let me know if this helps.

like image 187
James Avatar answered Oct 05 '22 13:10

James


I would just have left a comment under the question, but I don't have enough reputation. I encountered this very same issue, and after playing a little bit with the solution presented here, realized that a cleaner solution would be to call Focus() on the parent instead of making it topmost, set a timer, then remove topmost:

ChildWindow.Closed += delegate
{
    ChildWindow = null;
    parentWindow?.Focus();
};
like image 33
lexugax Avatar answered Oct 05 '22 13:10

lexugax