In a Windows Forms Application created in the standard way:
1 in the static Program.cs Class
2. a static 'Main method is executed which
3. calls 'Application.Run with
4. a new instance of a Form definition, the "main form," as its parameter.
There is no Application wide reference available to that instance of the "main form."
You can get a Collection of all currently open Forms in the running Application using:
private void btnShowMeTheOpenForms_Click(object sender, EventArgs e)
{
var openForms = Application.OpenForms;
for (int i = 0; i < openForms.Count; i++)
{
var f = openForms[i];
MessageBox.Show(string.Format("{0} {1}", i, f.Name));
}
}
While it will almost certainly be the case that the first (#0 index) in that FormCollection will be the "main form," I think it's always dangerous to rely on such an assumption.
So, you want an Application-wide reference to the main form: in your main Form's constructor:
public static Form MainForm;
public YourMainForm()
{
InitializeComponent();
MainForm = this;
}
You can then use YourMainForm.MainForm anywhere in any Form you created to get a pointer to the main form.
And, now, I'm going to tell you why you should not do this: by exposing your main form you are potentially allowing side effects ... through manipulation of any (objects) public fields, properties, methods in the main form: this is like leaving your house unlocked in a high-crime neighborhood with your money and keys in plain sight through the windows ... and other programmers will shun you if you do this, muttering something about a "smell" :)
What you should do to have that fresh-all-over-mint-feeling is carefully decide what objects on/in your main form you
absolutely must expose to any other secondary forms.
My bias is that you should strive to
never expose anything on a main form to a secondary form: that secondary forms should be dumb as logs, and themselves expose the minimum necessary to "outside entities," like the main form, or any other secondary form.
imho the figuring out the specific implementation for passing data/objects from one form to another is best dealt with ... for beginning students of .NET ... by focusing on specific programming tasks in prototype applications: there are several useful techniques that have become almost conventional.
If you post more specifics about your requirements for main form <=> secondary form interchange, I will respond.
The special keyword 'this will always return a reference to the current context (the instance of) the run-time object it is used in.