setting form properties during runtime

  • Thread starter Thread starter Jim Madsen
  • Start date Start date
J

Jim Madsen

OK--Beginner question--

I have a project with one form -- Form1. To change the text, why can't
I use "Form1.Text = something"? Instead I have to use
"Form1.ActiveForm.Text = Something". As an exercise, I rewrote a timer
app that I wrote in VB 5.0. You set the time, and when it runs, it
minimizes until the time is up, and then pops back up again and gives an
alerting sound. In VB 5.0, I was able to write the time to the forms
text property, while the timer was counting down and the form was
minimized, so you could see how much time was left by looking in the
task bar. Now, when I try to do this and the form minimizes, it throws
an exception when the time (ie form text) changes -- (I guess when the
form is minimized, it is no longer an active form). I'm confused.

Jim
 
I have a project with one form -- Form1. To change the text, why can't
I use "Form1.Text = something"?

Is form1 your instance name or your class name?

If it's your class name, you must refer to the current instance.

For example, if you displayed the new form as:

Dim _MyForm as new Form1

You can change the title by going _MyForm.Title = "SomeTitle"
 
Jim said:
I have a project with one form -- Form1. To change the text, why can't
I use "Form1.Text = something"? Instead I have to use
"Form1.ActiveForm.Text = Something".

Forms are Classes - always have been - so to set the property on any one
of them, you must have a reference to the object you want to manipulate.

VB no longer maintains a "default" reference (e.g. "form1") to each
Form. When you create the Form object, you have to hold that reference
and use it to access the Form object, as in

Sub New()
Dim f1 As New Form1
f1.Text = "Set the Form's Title"
...
End Sub

ActiveForm is a Shared method on the Form class that returns the
currently active Form anywhere in your application. Because your Form1
Inherits from Form, you get all the Shared method for free, so

Form1.ActiveForm

is the same as

System.Windows.Forms.Form.ActiveForm
In VB 5.0, I was able to write the time to the forms text property,
while the timer was counting down and the form was minimized,
so you could see how much time was left by looking in the task bar.
Now, when I try to do this and the form minimizes, it throws
an exception when the time (ie form text) changes -- (I guess when the
form is minimized, it is no longer an active form).
That's correct. There's no longer an ActiveForm in your application so
ActiveForm returns Nothing and Boom!

Your timer is part of your Form1 class, and you can alsways access the
Form (or, rather Class) it's within via the keyword "Me".

Private Sub tmrTick( ... ) _
Handles tmrTick.Elaped '?

Me.Text = DateTime.Now.ToString( "HH:mm:ss" )

End Sub

HTH,
Phill W.
 
Back
Top