views:

278

answers:

1

Hello, I'm encountering strange behavior with forms on a c# 3.5 app. On a button click, my form1 hides itself, creates a new form2, and shows form2. Form1 also contains the event method triggered when form2 closes. Here's the code inside Form1:

Form2 form2;

void button1_Click(object sender, EventArgs e)
    {           
        this.Hide();
        form2 = new form2();
        form2.Show();
        form2.FormClosed += new FormClosedEventHandler(form2_FormClosed);               
    }

void form2_FormClosed(object sender, FormClosedEventArgs e)
    {
        form2.Dispose();
        form2 = null; 
        this.Show();  
    }

Now, my problem is that sometimes when I open form2 (hiding form1), or when I close form2 (showing form1), the new form will come up on the screen for a blink and then hide itself. It's still open and I can click it from the taskbar to show it again, but the window itself is sent behind any other open windows. It looks like it opens up but minimizes instantly.

This behavior occurs randomly. Sometimes forms will open up and hide without a problem, but sometimes they'll lose focus over another window. I've tried using focus(), activate(), and topmost but all have failed to prevent the sudden hiding.

Does anyone know why is this happening and how to fix it?

Thanks.

+1  A: 

You hide your form too soon. For a brief moment, your app has no window that can contain the focus. That forces Windows to go hunting for another window to give the focus to, it will pick one from another application. That window will now be the foreground window, your second form will not get the focus and appear lower in the Z-order. The fix is simple:

void button1_Click(object sender, EventArgs e)
{           
    form2 = new form2();
    form2.Show();
    form2.FormClosed += new FormClosedEventHandler(form2_FormClosed);               
    this.Hide();  // Moved
}
Hans Passant
Thanks man, appreciate it.
Endo