Reputation: 702
Why is the messagebox shown before the form closes?
SomeForm myForm = new SomeForm();
myForm.Show();
MessageBox.Show("Some text");
Do I need to start a new thread, and wait for it to finish? I've never come across this problem before.
Upvotes: 1
Views: 420
Reputation: 203820
If it's important that the user not be able to interact with the main form while this other form is being shown then you can use myForm.ShowDialog
instead of Show
. ShowDialog
is a blocking function, so it won't return until the other form is closed. Show
, on the other hand, just shows the other form and then immediately returns without waiting for the form to be closed.
If it's intentional that the other form is not being shown modally, and you don't (or can't) make that change, then you can use events to show a message box when the other form is closed.
SomeForm myForm = new SomeForm();
myForm.FormClosed += (form, args) =>
{
MessageBox.Show("Some text");
};
myForm.Show();
This will add an event handler, which fires when the other form is closed, and executes the desired code at the appropriate time.
Upvotes: 1
Reputation: 12423
The reason for this is that myForm.Show();
starts the opening of a new window, however it is not a blocking call. It's not a dialog, it's a separate window, which runs on it's own.
If you want SomeForm to show as a Dialog (blocking window, waits for close to continue execution), then use ShowDialog
. If you want to wait till the window is opened before you show the MessageBox, then add the MessageBox to the OnLoaded on the SomeForm claa.
Upvotes: 1
Reputation: 245419
Your example never actually closes myForm
...only shows it. I would expect the code above to show myForm
and then immediately show the MessageBox
.
If you want myForm
to close before showing the MessageBox, you'll need to call myForm.Close()
at some point.
Upvotes: 1
Reputation: 9639
You need to use Form.ShowDialog() instead. Form.Show shows a modeless window, whereas Form.ShowDialog shows a modal form, i.e., that the user has to close before continuing.
Upvotes: 5