tags:

views:

175

answers:

3

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?

A: 

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.

Jon
Yes, I am using custom forms that are shown as a dialog box
Grzenio
+6  A: 

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]
Julien Poulin
It seems to return null whatever I do. Any ideas?
Grzenio
Updated answer when no Form has focus
Julien Poulin
Application.OpenForms works, cheers
Grzenio
The controls on the form which you want to access should probably have Public access set on them, if you haven't already done that.
Jon
A: 

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).

Mike J
Yes, I created a new thread, so its not blocked. I was looking for the answer provided by @Julien Poulin
Grzenio