Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF window hides behind the main app window. Trying to bring it to front

Tags:

c#

wpf

I have a 3rd part application which calls a simple WPF window which has a button which starts another WPF window.

MainApp -> Window1 -> Window2

The way the code is setup Window1 should be closed after starting Window2 which is working all well and good, but Window2 goes "behind" the MainApp window and hence is not visible. That is what I am trying to fix

Things that I have tried:

Window.TopMost: This is fine but the problem is that the window stays on top of all the windows when I Alt+Tab.

Activate() \ Focus(): These did not work

I also tried sending an Alt+Tab key stroke which seemed to fix the issue except that Window1 did not close at all.

I even tried combinations of Activate() \ Focus() \ TopMost from different SO posts but nothing seemed to work.

Code:

void btn_click()    // Window1
{
    Myclass.ShowMyDialog();
    res = DialogResult...
    Close();
}

// Myclass
public static void ShowMyDialog()
{
    s_window2 = new Window2();
    s.window2.Closed += OnClosed;
    s_window2.Show()
}
like image 923
ababeel Avatar asked Oct 27 '25 04:10

ababeel


1 Answers

Owner property should do the trick. Try below code:

    public MainWindow()
    {
        InitializeComponent();            
        this.Loaded += MainWindow_Loaded;                        
    }

    private void MainWindow_Loaded(object sender, RoutedEventArgs e)
    {
        Window1 win1 = new Window1();    //In your case, object of window2            
        win1.Owner = Application.Current.MainWindow;
        win1.Show();
    }
like image 119
Naresh Ravlani Avatar answered Oct 29 '25 19:10

Naresh Ravlani