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?
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.
You can get a reference to the currently active form by using the static Form.ActiveForm
property.
Edit: 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
in case its displayed using ShowDialog
:
// using Linq:
lastOpenedForm = Application.OpenForms.Cast<Form>().Last()
// or (without Linq):
lastOpenedForm = Application.OpenForms[Application.OpenForms.Count - 1]
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, ShowDialog
will "hold up" the thread that the form was created on and will not return control to the application (or, your test class) until ShowDialog
has finished processing, in which case your user code would continue on its path.
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).