Dela via


How to: Treat Forms as Objects

Forms are graphical objects that make up your application's user interface. Within Visual Basic, classes define how forms are displayed and what they can do. When a form is displayed at run time, Visual Basic creates an instance of the Form class that you can use like any other object. You can add custom methods and properties to forms and access them from other forms or classes in your application.

To create a new method for a form

  • Add a procedure declared as Public, as in the following code:

    ' Create a custom method on a form. 
    Public Sub PrintMyJob()
        ' Insert the code for your method here. 
    End Sub
    

To add a new field to a form

  • Declare a public variable in the form module, as in the following code:

    Public IDNumber As Integer
    

To access methods on a different form

  1. Create a new instance of the form whose methods you want to access. When you reference a form name, you are actually referencing the class the form belongs to, not the object itself.

    Note

    Visual Basic provides an implicit global variable with the same name as the form for each form class. For more information, see How to: Access a Form.

  2. Assign the form to an object variable. The object variable references a new instance of the form class.

    The following example correctly calls the PrintMyJob procedure:

    Dim newForm1 As New Form1
    newForm1.PrintMyJob()
    

    In the previous example, the new form is not displayed. It is not necessary to show a form object to use its methods. To display the new form, you need to add the following code:

    newForm1.Show()
    

See Also

Tasks

How to: Use the New Keyword

Concepts

Property Procedures