Close dialog form closes parent form

I ran into a strange problem. I am using KryptonForm in a project. I have a form (e.g. form1) and I need to open another form by clicking the button from this form. Here is the code:

void btn_click(object sender, EventArgs e) { Visible = false; ShowInTaskbar = false; var f = new Form2(); f.ShowDialog(); Visible = true; ShowInTaskbar = true; } 

The problem is that when closing Form2, it closes Form1 . I tried setting DialogResult = DialogResult.None from Form2 , but to no avail. Please help me.

I always use this technique, and it never has been.

+4
source share
2 answers

Yes, this code is a hassle. This happens incorrectly when the user closes the dialog. Then Windows should find another window where you can concentrate. There is nothing left in your application, the main window is invisible. Then he selects the window of another application. The odds are good, for example, that it will be a window inside Visual Studio. Large. Your basic form now disappears behind it.

You need to make sure your main window displays again before the dialog box closes. You can do this by subscribing to the FormClosing event handler dialog. For instance:

  private void button1_Click(object sender, EventArgs e) { using (var dlg = new Form2()) { dlg.StartPosition = FormStartPosition.Manual; dlg.Location = this.Location; dlg.FormClosing += (s, ea) => this.Show(); // <=== Here this.Hide(); if (dlg.ShowDialog() == DialogResult.OK) { // etc... } } } 
+6
source
  • Have you considered exceptions ? If Form2 throws an exception, your last statements Visible = true and ShowInTaskbar = true will fail. What happens when you try to do this:

     ShowInTaskbar = Visible = false; try { using (var f = new Form2()) // (added since Form2 is an IDisposable) { f.ShowDialog(); } } finally // make sure that the following gets executed even when { // exceptions are thrown during f.ShowDialog(): ShowInTaskbar = Visible = true; } 

  • What happens when you open a different form than Form2 inside this method?

    If the problem goes away, the problem is probably not in this method, but with Form2 .

    If the problem persists: are you sure you are doing the same in this method than in other methods where you apply the same technique?


  • Try deleting the first line and see if the problem persists. Or asked in a different way: only your parent form remains invisible or does it really become closed ?
0
source

All Articles