Closing one child form closes another child form

In the following Form1 code, two other Form s are opened, and then one of them is closed. As a result, the second child form also closes. Why?

 public partial class Form1 : Form { System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer { Interval = 2000 }; public Form1() { InitializeComponent(); ShowForm3(); (new Form2()).ShowDialog();//If this is changed to 'Show' - it doesn't get closed. } void ShowForm3() { Form3 f3 = new Form3(); f3.Show(); timer.Tick += (sender, e) => f3.Close(); timer.Start(); } } 

Form2 and Form3 are VS forms by default.

( Optional : this is a simple version of the source code. In the original (which, of course, is too long to publish here) this does not happen when executed from Visual Studio (neither Debug nor Release). This only happens when you install clickonce as an application, but then - even if I just click on the executable file (in the AppData folder). (Perhaps there is another piece of code that prevents it there when executed from VS, but I have not found it yet.) What could be the reason for this discrepancy? some type of optimization in clickonce that doesn't run well in Release mode?)

+4
source share
1 answer

Change your code to one that will work:

  public partial class Form1 : Form { System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer { Interval = 2000 }; public Form1() { InitializeComponent(); ShowForm3(); (new Form2()).ShowDialog(this); } void ShowForm3() { Form3 f3 = new Form3(); f3.Show(); timer.Tick += (sender, e) => f3.Close(); timer.Start(); } } 

Explanation: if you did not submit the parent form, the windows will be the active window as the parent using this method: GetActiveWindow and what happend is was:

when call form2.showDialog () // the parent window is form 3, because the GetActiveWindow method gets the displayed window and form1 is not active or shows

when you force the parent: when call form2.showDialog (this) // the parent window is form 1 because you defined a fixed

+5
source

Source: https://habr.com/ru/post/1498448/


All Articles