scroopy said:
I've created a form, MyForm, which Program creates an instance of in
Main() like this:
Application.Run(new MyForm());
but how do i get access to the instance of MyForm the app is using so
i can use its methods?
Forms are "event-driven" - they contain little bits of code (event handlers)
which gain control when activated from outside.
1. Create an empty form (MyForm), drag and drop onto it from the Toolbox one
label (label1) and one button (button1).
2. Run it - you see your form as in the designer with default text on the label
and button. The button depresses when you clickit, but it doesn't *do" anything.
3. Close it and return to the designer.
Your first place within the instance where you could do something and notice an
effect would be in the constructor.
4. In the constructor code (public MyForm() . . .) after the call to
"InitializeComponent()" add the line: this.label1.Text = "constuctor ran";
5. Run it again - you should see that the label text changed as per your line
of code.
Now add your own event handler.
6. View the form in the Designer and double click the button. You get an empty
handler created (button1_Click() . . .). Within that handler code add the line:
this.label1.Text = "button clicked";
7. Run it again - you should see the text change this time when you click the
button.
To answer your actual question - the "this" object represents your instance and
can be used to access instance members, can be passed to methods in other
classes, etc. The rest of Windows forms programming in c# is just variations on
this theme and is left as an exercise to the reader . . .
Happy coding,
-rick-