Chapter 14 Managing Windows Forms and Controls at Run Time 363
'Display the form as a modal dialog box
form2.ShowDialog()
When the user clicks the Create Form button, this event procedure creates a new form
with the title “My New Form” and a fixed border style. To use program code to create
a new form, you use the Dim statement and specify a variable name for the form
and the Form class, which is automatically included in projects as part of the System.
Windows.Forms namespace. You can then set properties such as Text, FormBorderStyle,
StartPosition, and DesktopBounds.
The StartPosition property is set to FormStartPosition.Manual to indicate that the
position will be set manually. The DesktopBounds property sizes and positions the
form and requires an argument of type Rectangle. The Rectangle type is a structure
that defines a rectangular region and is automatically included in Visual Basic projects.
Using the Dim statement, the Form2Rect variable is declared of type Rectangle
and initialized with the form position and size values. At the bottom of the event
procedure, the new form is opened as a dialog box using the ShowDialog method.
Although I usually recommend placing your Dim statements together at the top of the
form, here I have placed one a little lower in the code to make it easier to understand
the context and use of the variable.
Tip The complete Desktop Bounds program is located in the C:\Vb10sbs\Chap14\Desktop
Bounds folder.
- Click the Start Debugging button to run the program.
Visual Basic displays the first form on the desktop.
- Click the Create Form button.
Visual Basic displays the My New Form dialog box with the size and position you
specified in the program code, as shown here: