Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

winforms

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?

like image 321
Grzenio Avatar asked Jul 14 '09 17:07

Grzenio


1 Answers

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]
like image 68
Julien Poulin Avatar answered Sep 19 '22 11:09

Julien Poulin