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

后端 未结 2 970
长发绾君心
长发绾君心 2021-02-07 05:21

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 Te         


        
相关标签:
2条回答
  • 2021-02-07 05:54

    In my case, using VS2017, setting the property ShowInTaskbar as false did the trick.

    This is the complete code used to show the dialog:

    form.TopMost = true;
    form.StartPosition = FormStartPosition.CenterScreen;
    form.ShowInTaskbar = false;
    form.ShowDialog();
    

    P.S. After finding this, I've seen the same solution in Displaying Windows Forms inside unit test methods

    0 讨论(0)
  • 2021-02-07 05:59

    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();
    
    0 讨论(0)
提交回复
热议问题