How to make main window wait until a newly opened window closes in C# WPF?

21,112

Solution 1

Use ShowDialog instead of Show -

Win.ShowDialog();

From MSDN -

Opens a window and returns only when the newly opened window is closed.

Solution 2

Use ShowDialog() method as it Opens a window and returns only when the newly opened window is closed.

syntax

Win.ShowDialog();

Solution 3

Although ShowDialog works fine, you may set MainWindow.IsEnabled = false if you don't like that modal window. Sometimes it's useful to see the main window.

Share:
21,112
Arjun Ajith
Author by

Arjun Ajith

Logistics Functional Consultant on contract at a pretty big cement organization. Loved to code ever since, forced to Join SAP. Began functional consulting for an application built by someone else on top of SAP. Now provides bug fixes and makes functional specifications that make more sense to the programmer. Started to build web-services with java and deploy them on local GlassFish, but don't have enough resources to buy my own server. Building a pretty sick Android application that the masses would love but don't have anyone to help. Sometimes I am lost at where this is all going. But I will find my day, my time and bring it to the world.

Updated on July 16, 2022

Comments

  • Arjun Ajith
    Arjun Ajith almost 2 years

    I am new to WPF as well as C#, please bear with me.

    I have a main window which opens up a new window. Now this new window is a prompt whether or not to overwrite a file, and the main window accesses a public variable in the new window to check for the prompt's result.

    But I can't get the main window processing to wait until the new window closes.

     Window1 Win = new Window1();
     Win.Show();
    
     if (Win.pr_res == 1)
     {
          abc.Text = "File to be overwritten";
          File.Delete(_destination);
          Start();
     }
     else
     {
          abc.Text = "Operation Aborted";
     }
    

    I tried adding a while loop checking another public boolean in the main window, but that just hangs the entire program.

     while(!_closecheck);
    

    Any suggestions are welcome.

  • Pang
    Pang about 7 years
    This sounds like a repeat of this existing answer and also this existing answer.