15

I am making a Win Forms application to learn more since I don't have much experience with it. In my program, in the main form, I have a button. Clicking it launches another form. The code is as follows:

 private void btn_AddCat_Click(object sender, EventArgs e)
        {
            this.Invoke(new MethodInvoker(() =>
            {
                form_NewCat NewCatForm = new form_NewCat();
                NewCatForm.Show();
            }));

            MessageBox.Show("Oops!");            
        }

The problem is, when the new form is launched, I want execution of the code behind the main form to pause at that point until the new form is closed. As an example, in the above code, I do not want 'Oops!' to get printed until the new form is closed. How can I achieve that?

xbonez
  • 40,730
  • 48
  • 157
  • 236

4 Answers4

23

Change the line

NewCatForm.Show();

to

NewCatForm.ShowDialog();
Venemo
  • 17,817
  • 11
  • 84
  • 120
18

You don't need to invoke when you are in the UI thread. And you are in the UI thread in a button-click eventhandler.

private void btn_AddCat_Click(object sender, EventArgs e)
{
    form_NewCat NewCatForm = new form_NewCat();
    var dialogResult = NewCatForm.ShowDialog();
    MessageBox.Show("Oops!");            
}

You can check the dialogResult for OK, Cancel, Yes, No, etc if your form_NewCat sets this.DialogResult to any value before closing. This is the usual way to signal how the user exited the form/dialog.

Albin Sunnanbo
  • 45,452
  • 8
  • 67
  • 106
  • I changed the event handler to exactly what u showed. The new form has a cancel button. The event handler for the cancel button executes this.Close(). However, when I hit the cancel button, the form disappears and then reappears again. Hitting cancel again closes the form. Why is that so? My new form is being displayed twice. – xbonez Dec 05 '10 at 17:33
  • @xbonez, strange, are you sure you don't have any other code that shows the form? Like in the constructor? – Albin Sunnanbo Dec 05 '10 at 19:04
  • I was in situation where i can't use ShowDialog(), I added event to form that i want to open and execute rest of the code on closeing `Form frm = new frmScreenCapture(); frm.FormClosed += frm_FormClosed; frm.Show();` – sairfan May 25 '18 at 22:09
6

Simply change Show to ShowDialog; this also let's you get a return value to indicate whether the form considered itself exiting with a specific status (ok, cancel, etc).

Marc Gravell
  • 976,458
  • 251
  • 2,474
  • 2,830
6

You want a modal dialog and I think you need NewCatForm.ShowDialog();

David Heffernan
  • 587,191
  • 41
  • 1,025
  • 1,442