我怎样才能获得引用当前活动模式的形式?形式、模式

2023-09-04 01:17:57 作者:二的狠有范

我写一个小班用于驱动一个双赢的形式应用的集成测试。测试驱动程序类访问的主要形式,并查找需要使用的名字,并用它来驱动测试控制。为了找到我遍历Control.Controls树控制。不过,我碰到困难时,我想,以控制在一个对话框窗口(显示为一个对话框,自定义表单)。我怎样才能得到它持有?

I am writing a small class for driving integration testing of a win form application. The test driver class has access to the main Form and looks up the control that needs to be used by name, and uses it to drive the test. To find the control I am traversing the Control.Controls tree. However, I get stuck when I want to get to controls in a dialog window (a custom form shown as a dialog). How can I get hold of it?

推荐答案

您可以通过使用静态Form.ActiveForm属性。

You can get a reference to the currently active form by using the static Form.ActiveForm property.

编辑:如果没有表格的焦点, Form.ActiveFor​​m 返回。 要解决这个问题的方法之一是使用 Application.OpenForms 收集和检索的最后一个项,女巫将成为活动表格当使用的ShowDialog 显示它:

If no Form has the focus, Form.ActiveForm will return null. One way to get around this is to use the Application.OpenForms collection and retrieve the last item, witch will be the active Form when it is displayed using ShowDialog:

// using Linq:
lastOpenedForm = Application.OpenForms.Cast<Form>().Last()
// or (without Linq):
lastOpenedForm = Application.OpenForms[Application.OpenForms.Count - 1]