Form.ShowDialog()不显示启用了调试的窗口 [英] Form.ShowDialog() does not display window with debugging enabled
问题描述
我已经在单元测试项目中创建了一个测试,我想使用其 ShowDialog()
函数弹出 Form :
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;
}
我希望此测试能够达到 ShowDialog()
,并无限期"运行,直到关闭窗口.但是,当我通过调试"运行此测试时,该测试到达 ShowDialog()
,并且没有任何形式出现.奇怪的是,如果我运行未经调试",则同样的测试会起作用.
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.
其他说明:
-
Show()
是不可取的,因为它不等待窗口关闭继续.(此外...它不起作用.) - 同一代码先前已在使用.NET 3.5的另一个项目中工作.这只是说
ShowDialog()
策略肯定曾经起作用过.(是的,我直接复制了该工作代码.) - 我的问题类似于这个问题,但是,我的表单是不是另一个对话框的子级,也不存在于父UI线程中.
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.
推荐答案
尽我所能避免构建使用 System.Windows.Forms
的单元测试,但我遇到了一种奇怪的情况:也需要此方法,并通过处理 Load
事件并显式设置 Visible = true
来解决此问题.当从测试方法中调用ShowDialog时,这将强制显示窗体.
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();
这篇关于Form.ShowDialog()不显示启用了调试的窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!