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?
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
when it is displayed using ShowDialog
:
// using Linq:
var lastOpenedForm = Application.OpenForms.Cast<Form>().Last()
// or (without Linq):
var lastOpenedForm = Application.OpenForms[Application.OpenForms.Count - 1]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With