The opening MessageBox is deactivating your child form, therefore it is closed.
When opening a MessageBox without telling its parent, the current active window is used, in this case your child form. When the MessageBox's parent (child form) is closed, also the MessageBox get's closed.
If you want the main form to open the MessageBox, even it is called from another window, use an overload that uses IWin32Window owner
-Parameter.
public partial class MainForm : Form {
public MainForm() {
InitializeComponent();
}
private void button_Click(object sender, EventArgs e) {
var form = new ChildForm(this);
form.Show();
}
// Method called by ChildForm
public void OpenMessageBox() {
IWin32Window owner = this;
MessageBox.Show(owner, "MessageBox opened from MainForm, but called from within ChildForm");
}
}
I see one problem with your code. You are delegating control logic from MainForm into ChildForm back into MainForm. Try to let MainForm control the logic flow by using the ChildForm's FormClosed-Event. Note that this is an optional step, let's say a cleaner way to get that behavior you wan't to achieve.
private void button_Click(object sender, EventArgs e) {
var form = new ChildForm(this);
form.FormClosed += ChildFormClosed;
form.Show();
}
private void ChildFormClosed(object sender, FormClosedEventArgs formClosedEventArgs) {
var childForm = (Form)sender;
childForm.FormClosed -= ChildFormClosed;
MessageBox.Show("MessageBox opened from MainForm");
}
}