beginner: Windows form Q

  • Thread starter Thread starter scroopy
  • Start date Start date
S

scroopy

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?

ta
 
Well, where do you want to do it? If you mean within the form (button-clicks
etc) then that would be "this" within the MyForm class; if you mean within
your Main() method, then something like:

using(MyForm form = new MyForm()) {
// can access form here
Application.Run(form);
// can access form here
}

*HOWEVER*; note that once you leave .Run(), then the user has closed your
form, and before then it hasn't been opened, so not really much benefit in
being able to get at it...
One use of the above approach is when you want to respond to external events
etc, but I doubt that this is what you are trying to do. So, what exactly
/are/ you trying to do?

Marc
 
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-
 
You define a class called "MyForm" which inherits System.Windows.Forms.Form
in your project.

--
HTH,

Kevin Spencer
Microsoft MVP
Professional Numbskull

This is, by definition, not that.
 
Back
Top