简体   繁体   中英

WPF Window under all other windows after making window visible from being collapsed

I am having some very frustrating issues with my WPF window. The design I was going for is:

When the user minimizes the window it will minimize to a system tray icon (hide the window and icon on start bar). When the user right clicks on the icon, a context menu will show up with options and one of them will say open, which will open the app (show window again / unhide window agian). The user could also double click the icon as well.

Pretty simple right?

I have no issues minimzing to the task bar, I simply do the following on the closing event of the window:

e.Cancel = true;
this.Visibility = Visibility.Collapsed;

However, I am having issues properly restoring the window. I simply do this on the context menu click or icon double click event:

this.Visibility = Visibility.Visible;
this.Activate();

The issue is that the window is once again on the start bar with its icon but it is behind every single window the user has open. I want it so when the user goes to open the window it will be the top most window. I do not always want it to be the topmost, just only when they want to make it visible again.

I have tried many things like setting the show activate on the window to true, waiting a second after making it visible to then activate the window, activating the window multiple times (worked a few times but was maybe 1 out of 10 tries), etc..

I don't think showing / hiding a window should be this annoying and I am not really sure what I am doing wrong.

Any help is appreciated, thank you.

Only after posting this did I realize, the application minimizes first before hiding. When I show the window, it was showing as minimized.

After knowing this issue I was able to fix the issue. This may help others who do decide to hide the window after minimizing.

EDIT Here is the code I used to hide the window (this is called after the event fires for state changed [minimized]):

Application.Current.MainWindow.Visibility = Visibility.Collapsed;
Application.Current.MainWindow.WindowState = WindowState.Normal;

You will notice I set the window state back to normal after I hide it. Even though the window is hidden and not being rendered it will in memory restore the window location / size.

Then when I want to see the window again I just do:

Application.Current.MainWindow.Visibility = Visibility.Visible;

Which will show the window just fine!

Hopes this helps someone out there!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM