How to make a WPF window be on top of all other windows of my app (not system wide)?

后端 未结 19 2976
南笙
南笙 2020-12-14 05:42

I want my window to be on top of all other windows in my application only. If I set the TopMost property of a window, it becomes on top of all windows of al

19条回答
  •  北海茫月
    2020-12-14 05:58

    I ran into a very similar situation as you. Most of the searches I came across stated all I needed to do was set the Owner of the windows I wish to be Topmost to the main window or whatever window that called Show.

    Anyways, I'll go ahead and post a solution that worked well for me.

    I created event handlers for Window.Activated and Window.Deactived in the window that was supposed to be Topmost with respect to my application.

    private void Window_Activated(object sender, EventArgs e)
    {
        Topmost = true;
    }
    
    private void Window_Deactived(object sender, EventArgs e)
    {
        if(Owner == null || Owner.IsActive)
            return;
        bool hasActiveWindow = false;
        foreach(Window ownedWindow in Owner.OwnedWindows)
        {
            if(ownedWindow.IsActive)
                hasActiveWindow = true; 
        }
    
        if(!hasActiveWindow)
            Topmost = false;
    }
    

    It works great for me. Hopefully this is useful to someone else out there. :o)

提交回复
热议问题