Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Form.ShowDialog() does not display window with debugging enabled

I've created a test within a Unit Test Project, in which I want pop up a Form using its ShowDialog() function:

[TestMethod]
public void TestDialog()
{
  // This class inherits from Form
  TestForm serviceTestForm = new TestForm("My test form"); 
  serviceTestForm.ShowDialog();

  return;
}

I expect this test to reach ShowDialog(), and run 'indefinitely', until I close the window. However, when I run this test "with debugging", the test reaches ShowDialog(), and no form appears. Strangely enough, this same exact test works if I run "without debugging."

I need to be able to run the test "with debugging" and have the window display.

Other notes:

  • Show() is not desirable, as it doesn't wait for the window to close to continue. (Besides... it doesn't work.)
  • This same code has worked previously on another project utilizing .NET 3.5. This is only to say the ShowDialog() strategy has definitely worked before. (And yes, I copied that working code over directly.)
  • My question is similar to this one, however, my form is not a child of another dialog, and does not live within a parent UI thread.
like image 287
David Elner Avatar asked Jul 22 '13 21:07

David Elner


People also ask

What is the difference between form show () and form ShowDialog ()?

Show() method shows a windows form in a non-modal state. ShowDialog() method shows a window in a modal state and stops execution of the calling context until a result is returned from the windows form open by the method.

What is ShowDialog C#?

ShowDialog() Shows the form as a modal dialog box. ShowDialog(IWin32Window) Shows the form as a modal dialog box with the specified owner.


1 Answers

As much as I try to avoid building unit tests that use System.Windows.Forms, I ran into an odd case where I needed this as well and solved it by handling the Load event and explicitly setting Visible = true. This forces the form to visible when ShowDialog is called from the test method.

private void form1_Load(object sender, EventArgs e)
{
    // To support calling ShowDialog from test method...
    this.Visible = true;
    ...
}

Alternatively, just observe the form instance from your test method and do the same there instead. At least this mitigates the issue further in that it keeps the hack out of your form's code.

var frm = new Form1();
frm.Load += (sender, e) => (sender as Form1).Visible = true;
frm.ShowDialog();
like image 196
blins Avatar answered Oct 28 '22 01:10

blins