I have a form in a winforms app. When I press a button, it loads a modal message box with the options yes and no.
This is fine, but when I press no, I want to close both the dialog box and the form where the button which launched the dialog box (the sender) is.
So the app structure is like this:
Main app window > press menu item to launch new form (connection setup) > press button on this form to launch message box.
Two windows are open (connection setup form and dialog box), which I both want closed.
How could I do this?
Click the x button from the top right corner of the dialog box that you'd like to close. Clicking this button should close the box and make it vanish. However, this could sometimes make alternate other boxes open up instead.
If you want to get rid of the dialog box, there are three ways you can do it. I find the easiest way is to simply press Esc. You can also press Ctrl+F4, or you can use Tab to select the Cancel button and then press Enter.
Right-click the icon referring to the dialog box from the Windows taskbar and click “Close”. Using the Task Manager: Open the Task Manager using the search bar(“ctrl + alt + del”), right-click on the application that you want to close and click on “End task”.
There are 3 types of dialog boxes: modeless, modal, and system modal. Modal dialog boxes are generally used inside a program, to display messages, and to set program parameters.
In your yes-no modal form, just set DialogResult
to No when you press the No button, like:
private void noButton_Click(object sender, EventArgs e)
{
this.DialogResult = System.Windows.Forms.DialogResult.No;
}
and the modal form will automatically close when you click No
Then when you open your modal form do something like this (in the connection setup form):
var modalForm = new YesNoForm();
if (modalForm.ShowDialog() == DialogResult.No)
{
this.Close(); // close the connection setup form
}
EDIT
I thought your yes-no modal form was custom, if it's a simple MessageBox, just do:
var dlgResult = MessageBox.Show("Yes or no ?","?",MessageBoxButtons.YesNo);
if(dlgResult == System.Windows.Forms.DialogResult.No)
{
this.Close(); // close the connection setup form
}
as already suggested in other answers
Something like this:
DialogResult result = MessageBox.Show("dialog", "modal", MessageBoxButtons.YesNo);
if (result == DialogResult.No)
{
this.Close();
}
For custom modal dialogs code will be similar.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With