C# 如何获得对当前活动模态表单的引用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1126829/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 08:49:19  来源:igfitidea点击:

How can I get the reference to currently active modal form?

c#.netwinforms

提问by Grzenio

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?

我正在编写一个小类来驱动一个 win 表单应用程序的集成测试。测试驱动程序类可以访问主 Form 并查找需要按名称使用的控件,并使用它来驱动测试。为了找到控件,我正在遍历 Control.Controls 树。但是,当我想访问对话框窗口(显示为对话框的自定义表单)中的控件时,我会卡住。我怎样才能抓住它?

采纳答案by Julien Poulin

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

您可以使用静态Form.ActiveForm属性获取对当前活动表单的引用。

Edit: If no Formhas the focus, Form.ActiveFormwill return null.
One way to get around this is to use the Application.OpenFormscollection and retrieve the lastitem, witch will be the active Formwhen it is displayed using ShowDialog:

编辑:如果没有Form焦点,Form.ActiveForm将返回null
解决此问题的一种方法是使用Application.OpenForms集合并检索最后一个项目,Form当使用ShowDialog以下方法显示时,女巫将处于活动状态:

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

回答by Jon Onstott

I'm not sure if you can access controls on a pre-built dialog box; they seem all packaged together. You may have more luck building a dialog box of your own that does what you want it to do. Then you can access the .Controls inside of it.

我不确定您是否可以访问预建对话框上的控件;它们似乎都打包在一起。您可能会更幸运地构建自己的对话框来执行您希望它执行的操作。然后您可以访问其中的 .Controls 。

回答by Mike J

Correct me if i'm wrong, though, it sounds as if you are possibly attempting to access the controls on the dialog form when it's not quite possible to.

如果我错了,请纠正我,听起来好像您可能试图在不太可能的情况下访问对话框窗体上的控件。

What I mean is, ShowDialogwill "hold up" the thread that the form was created on and will not return control to the application (or, your test class) until ShowDialoghas finished processing, in which case your user code would continue on its path.

我的意思是,ShowDialog将“阻止”创建表单的线程,并且ShowDialog在完成处理之前不会将控制权返回给应用程序(或您的测试类),在这种情况下,您的用户代码将继续其路径。

Try accessing or manipulating the controls from a separate thread (in this case, refactor the test driver class to spawn a separate thread for each new form that must be displayed and tested).

尝试从单独的线程访问或操作控件(在这种情况下,重构测试驱动程序类,为每个必须显示和测试的新表单生成一个单独的线程)。