I am using Visual Studio 2010, C# .NET 4.0. I have 3 forms: Form1, Form2, Form3.
In Form1 I have a button to open Form2:
private void button1_Click(object sender, EventArgs e)
{
Form2 f = new Form2();
f.Show();
}
In Form2 I have a private Form3 variable always pointing to the same Form3:
private Form3 f = new Form3();
And a button to open it as a dialog:
private void button1_Click(object sender, EventArgs e)
{
f.ShowDialog();
}
In Form3 I just have a button to hide the form:
private void button1_Click(object sender, EventArgs e)
{
this.Hide();
}
The problem is that having the situation that Form2 is in front of Form1, and Form3 in front of Form2, when I click the button of Form3 to hide it, it not only hides itself but sends Form1 to the back of all of the other Windows.
This only happens when there is a window of another program (such as Windows Explorer) in the background of Form1. It seems like a bug开发者_JS百科. What do you think?
Yes, this cannot work properly by design. A dialog disables all of the windows that your program displays. So that it is modal. When you hide the dialog, there are no windows left that can get the focus. Windows is forced to find another window to give the focus to. That will be a window owned by another application. Your own windows will now hide behind it.
There are more side effects, the dialog will also close. Necessary because otherwise the user can never get back to your program anymore since all windows are disabled. This is all unsurprising behavior. Bug would be a strong word, but it would of course work better if it first re-enabled all windows before closing the dialog. But closing the dialog is already undesirable behavior.
Don't call Hide() for a dialog. Just set the DialogResult property to DialogResult.Cancel to achieve the exact same effect, minus the focus problem. You do have to reset it back to None if you want to display the dialog again. That's a real bug.
By the documentation. Form.Close method doesn't dispose forms shown by Form.ShowDialog method. Quote:
The two conditions when a form is not disposed on Close is when (1) it is part of a multiple-document interface (MDI) application, and the form is not visible; and (2) you have displayed the form using ShowDialog. In these cases, you will need to call Dispose manually to mark all of the form's controls for garbage collection.
So, maybe there are ways to return focus to your application (e.g. via Windows API). But it is much more convenient to call Form.Close manually on dialog windows.
精彩评论