Appendix J

Form Objects

This appendix describes the most useful properties, methods, and events provided by the Windows Form class.

The Form class inherits indirectly from the Control class (Control is the Form class’s “great-grandparent”), so in many ways, a form is just another type of control. Except where overridden, Form inherits the properties, methods, and events defined by the Control class. Chapter 8, “Using Windows Forms Controls,” discusses some of the more useful properties, methods, and events provided by the Control class, and most of those apply to the Form class as well. Appendix A, “Useful Control Properties, Methods, and Events,” summarizes the Control class’s most useful properties.

PROPERTIES

The following table describes some of the most useful Form properties.

PROPERTY DESCRIPTION
AutoScroll Determines whether the form automatically provides scroll bars when it is too small to display all of the controls it contains.
AutoScrollMargin If AutoScroll is True, the control will provide scroll bars if necessary to display its controls plus this much margin.
AutoScrollPosition Adjusts the AutoScroll scroll bars so this point on the form is placed at the upper-left corner of the visible area (if possible). For example, if a button has location (100, 20), the statement AutoScrollPosition = New Point(100, 20) scrolls the form so the button is in the upper-left corner of the visible area.
BackColor Determines the form’s background color.
BackgroundImage Determines the image displayed in the form’s background.
BackgroundImageLayout Determines how the BackgroundImage is displayed. This can be None (the image is displayed at up to normal scale, or compressed, if necessary, to make it fit vertically or horizontally), Tile (the image is tiled to fill the form), Center (the image is centered on the form at up to normal scale, or compressed, if necessary, to make it fit vertically or horizontally), Stretch (the image is resized to fill the form exactly), or Zoom (the image is resized to fill the form as much as possible without distorting it).
Bottom Returns the distance between the form’s bottom edge and the top edge of its container.
Bounds Determines the form’s size and location within its container. These bounds include the form’s client and non-client areas (such as the borders and caption area).
CancelButton Determines the button that clicks when the user presses the Escape key. This button basically gives the form a cancel action. If the form is being displayed modally, clicking this button either manually or by pressing Escape automatically closes the form.
Capture Determines whether the form has captured mouse events. While this is True, all mouse events go to the form’s event handlers. For example, pressing the mouse button sends the form a MouseDown event even if the mouse is over a control on the form or if it is off of the form completely.
ClientRectangle Returns a Rectangle object representing the form’s client area.
ClientSize Gets or sets a Size object representing the client area’s size. If you set this value, the form automatically adjusts to make the client area this size while allowing room for its non-client areas (such as borders and title bar).
ContainsFocus Returns True if the form or one of its controls has the input focus.
ContextMenuStrip Gets or sets the form’s context menu. If the user right-clicks the form, Visual Basic automatically displays this menu. Note that controls on the form share this menu unless they have context menus of their own. Also note that some controls have their own context menus by default. For example, a TextBox displays a Copy, Cut, Paste menu, unless you explicitly set its ContextMenu property.
ControlBox Determines whether the form displays a control box (the Minimize, Maximize, Restore, and Close buttons) on the right side of its caption area.
Controls Returns a collection containing references to all of the controls on the form. This includes only the controls contained directly within the form, and not controls contained within other controls.
Cursor Determines the cursor displayed by the mouse when it is over the form.
DesktopBounds Determines the form’s location and size on the desktop as a Rectangle.
DesktopLocation Determines the form’s location on the desktop as a Point.
DialogResult Gets or sets the form’s dialog box result. If code displays the form modally using its ShowDialog method, the method returns the DialogResult value the form has when it closes. Setting the form’s DialogResult value automatically closes the dialog box. Triggering the form’s CancelButton automatically sets DialogResult to Cancel and closes the dialog box.
DisplayRectangle Gets a Rectangle representing the form’s display area. This is the area where you should display things on the form. In theory, this might not include all of the client area and could exclude form decorations, although in practice it seems to be the same as ClientRectangle.
Enabled Determines whether the form will respond to user events. If the form is disabled, all of its controls are disabled and drawn grayed out. The user can still resize the form, and its controls’ Anchor and Dock properties still rearrange the controls accordingly. The user can also click the form’s Minimize, Maximize, Restore, and Close buttons. Note that you cannot display a form modally using ShowDialog if it is disabled.
Font Determines the form’s font.
ForeColor Determines the foreground color defined for the form.
FormBorderStyle Determines the form’s border style. This can be None, FixedSingle, Fixed3D, FixedDialog, Sizeable, FixedToolWindow, or SizeableToolWindow.
Handle Returns the form’s integer window handle (hWnd). You can pass this value to API functions that work with window handles.
HasChildren Returns True if the form contains child controls.
Height Determines the form’s height.
HelpButton Determines whether the form displays a Help button with a question mark in the caption area to the left of the close button. The button is only visible if the MaximizeBox and MinimizeBox properties are both False. If the user clicks the Help button, the mouse pointer turns into a question mark arrow. When the user clicks the form, Visual Basic raises the form’s HelpRequested event. The form can provide help based on the location of the click and, if it provides help, it should set the event handler’s hlpevent.Handled parameter to True.
Icon Determines the form’s icon displayed in the left of the form’s caption area, in the taskbar, and by the Task Manager. Typically, this icon should contain images at the sizes 16 x 16 pixels and 32 x 32 pixels, so different displays can use an image with the correct size without resizing.
KeyPreview Determines whether the form receives key events before they are passed to the control with the input focus. If KeyPreview is True, the form’s key event handlers can see the key, take action, and hide the key from the control that would normally receive it, if necessary.
Left Determines the distance between the form’s left edge and the left edge of its container.
Location Determines the coordinates of the form’s upper-left corner.
MainMenuStrip Gets or sets the form’s main menu.
MaximizeBox Determines whether the form displays a Maximize button on the right of its caption area.
MaximumSize This Size object determines the maximum size the form can take.
MinimizeBox Determines whether the form displays a Minimize button on the right of its caption area.
MinimumSize This Size object determines the minimum size the form can take.
Modal Returns True if the form is displayed modally.
Name Gets or sets the form’s name. Initially, this is the form’s class name, but your code can change it to anything, possibly even duplicating another form’s name.
Opacity Determines the form’s opacity level between 0.0 (transparent) and 1.0 (opaque). At design time this is displayed as a percentage 0% (transparent) to 100% (opaque).
OwnedForms Returns an array listing this form’s owned forms. To make this form own another form, call this form’s AddOwnedForm method, passing it the other form. Owned forms are minimized and restored with the owner and can never lie behind the owner. Typically, they are used for things like toolboxes and search forms that should remain above the owner form.
Region Gets or sets the region that defines the area that the form can occupy. Pieces of the form that lie outside of the region are clipped.
Right Returns the distance between the form’s right edge and the left edge of its container.
ShowIcon Determines whether the form displays an icon in its title bar. If this is False, the system displays a default icon in the taskbar and Task Manager if ShowInTaskbar is True.
ShowInTaskbar Determines whether the form is displayed in the taskbar and Task Manager.
Size Gets or sets a Size object representing the form’s size, including client and non-client areas.
SizeGripStyle Determines how the resize grip is shown in the form’s lower-right corner. This can be Show, Hide, or Auto.
StartPosition Determines the form’s position when it is first displayed at run time. This can be Manual (use the size and position specified by the form’s properties), CenterScreen (center the form on the screen taking the taskbar into account), WindowsDefaultLocation (use a default position defined by Windows and use the form’s specified size), and WindowsDefaultBounds (use a default position and size defined by Windows).
Tag Gets or sets an object associated with the form. You can use this for whatever purpose you see fit.
Text Determines the text displayed in the form’s caption.
Top Determines the distance between the form’s top edge and the top edge of its container.
TopMost Determines whether the form is a topmost form. A topmost form always sits above all other non-topmost forms, even when the other forms have the input focus.
TransparencyKey Gets or sets a color that determines the areas of the form that are shown as transparent. This applies to the form itself and any controls it contains. For example, if you set TransparencyKey to the color Colors.Control, the whole form and the bodies of many of its controls are invisible, so you will see text and borders floating above whatever forms lie behind.
UseWaitCursor Determines whether the form is currently displaying the wait cursor.
Visible Determines whether the form is visible. If the form is not visible, the user cannot interact with it. If you set Visible = False, the form’s icon is also removed from the taskbar and Task Manager.
Width Determines the form’s width.
WindowState Gets or sets the form’s state. This can be Normal, Minimized, or Maximized.

METHODS

The following table describes some of the most useful Form methods.

METHOD DESCRIPTION
Activate Activates the form and gives it the focus. Normally, this pops the form to the top. Note that forcing a form to the top takes control of the desktop away from the user, so you should use this method sparingly. For example, if the user dismisses one form, you might activate the next form in a logical sequence. You should not activate a form to get the user’s attention every few minutes.
AddOwnedForm Adds an owned form to this form. Owned forms are minimized and restored with the owner and can never lie behind the owner. Typically, they are used for things like toolboxes and search forms that should remain above the owner form.
BringToFront Brings the form to the top of the Z-order. This applies only to other forms in the application. This form will pop to the top of other forms in this program, but not forms in other applications.
Close Closes the form. The program can still prevent the form from closing by catching the FormClosing event and setting e.Cancel to True.
Contains Returns True if a specified control is contained in the form. This includes controls inside GroupBox controls, Panel controls, and other containers, which are not listed in the form’s Controls collection.
CreateGraphics Creates a Graphics object that the program can use to draw on the form’s surface. Note that the Paint event handler provides a Graphics object in its e.Graphics parameter when the form needs to be redrawn. You should use that object rather than a new one returned by CreateGraphics while inside a Paint event handler. Otherwise, the Paint event handler’s version will draw over anything that you draw using the object returned by CreateGraphics.
GetChildAtPoint Returns a reference to the child control at a specific point. Note that the control is the outermost control at that point. For example, if a GroupBox contains a Button and you call GetChildAtPoint for a point above the Button, GetChildAtPoint returns the GroupBox. To find the Button, you would need to use the GroupBox control’s GetChildAtPoint method. Note also that the position of the Button within the GroupBox is relative to the GroupBox control’s origin, so you would need to subtract the GroupBox control’s position from the X and Y coordinates of the point relative to the form’s origin.
GetNextControl Returns the next control in the tab order. Parameters indicate the control to start from and whether the search should move forward or backward through the tab order.
Hide Hides the form. This sets the form’s Visible property to False.
Invalidate Invalidates some or all of the form’s area and generates a Paint event.
PointToClient Converts a point from screen coordinates into the form’s coordinate system.
PointToScreen Converts a point from the form’s coordinate system into screen coordinates.
RectangleToClient Converts a rectangle from screen coordinates into the form’s coordinate system.
RectangleToScreen Converts a rectangle from the form’s coordinate system into screen coordinates.
Refresh Invalidates the form’s client area and forces it to redraw itself and its controls.
RemoveOwnedForm Removes an owned form from this form’s OwnedForms collection.
Scale Resizes the form and the controls it contains by a scale factor. A second overloaded version scales by different amounts in the X and Y directions. Note that this doesn’t change the controls’ font sizes, just their dimensions.
ScrollControlIntoView If the form has AutoScroll set to True, this scrolls to make the indicated control visible.
SelectNextControl Activates the next control in the tab order. Parameters indicate the control to start at, whether the search should move forward or backward through the tab order, whether the search should include only controls with TabStop set to True or all controls, whether to include controls nested inside other controls, and whether to wrap around to the first/last control if the search passes the last/first control.
SendToBack Sends the form to the back of the Z-order. This puts the form behind all other forms in all applications, although it does not remove the focus from this form.
SetAutoScrollMargin If AutoScroll is True, this method sets the AutoScroll margin. The control will provide scroll bars if necessary to display its controls plus this much margin.
SetBounds Sets some or all of the form’s bounds: X, Y, Width, and Height.
SetDesktopBounds Sets the form’s position and size in desktop coordinates. See SetDesktopLocation for more information.
SetDesktopLocation Sets the form’s position in desktop coordinates. Desktop coordinates include only the screen’s working area and do not include the area occupied by the taskbar. For example, if the taskbar is attached to the left edge of the screen, the point (0, 0) in screen coordinates is beneath the taskbar. However, the point (0, 0) in desktop coordinates is just to the right of the taskbar. If you set the form’s location to (0, 0), part of the form is hidden by the taskbar. If you set the form’s desktop location to (0, 0), the form is visible just to the right of the taskbar.
Show Displays the form. This has the same effect as setting the form’s Visible property to True.
ShowDialog Displays the form as a modal dialog box. The user cannot interact with other parts of the application before this form closes. Note that some other processes may still be running within the application. For example, a Timer control on another form still raises Tick events and the program can still respond to them.

EVENTS

The following table describes some of the most useful Form events.

EVENT DESCRIPTION
Activated Occurs when the form activates.
Click Occurs when the user clicks the form. Normally, if the user clicks a control, the control rather than the form receives the Click event. If the form’s Capture property is set to True, however, the event goes to the form.
Deactivate Occurs when the form deactivates.
DoubleClick Occurs when the user double-clicks the form. Normally, if the user double-clicks a control, the control rather than the form receives the DoubleClick event. If the form’s Capture property is set to True, however, the first click goes to the form and the second goes to the control.
FormClosed Occurs when the form is closed. The program can still access the form’s properties, methods, and controls, but it is definitely going away. See also the FormClosing event. Note that if the program calls Application.Exit, the form’s FormClosed and FormClosing events do not occur. If you want the program to free resources before the form disappears, it should do so before calling Application.Exit.
FormClosing Occurs when the form is about to close. The program can cancel the close (for example, if some data has not been saved) by setting the event handler’s e.Cancel parameter to True.
GotFocus Occurs when focus moves into the form.
HelpRequested Occurs when the user requests help from the form, usually by pressing F1 or by pressing a context-sensitive Help button (see the HelpButton property) and then clicking a control on the form. Help requests move up through control containers until a HelpRequested event sets its hlpevent.Handled parameter to True. For example, suppose that the user sets focus to a TextBox contained in the form and presses F1. The TextBox control’s HelpRequested event handler executes. If that routine doesn’t set hlpevent.Handled to True, the event bubbles up to the TextBox control’s container, the form, and its HelpRequested event handler executes.
KeyDown Occurs when the user presses a keyboard key down.
KeyPress Occurs when the user presses and releases a keyboard key.
KeyUp Occurs when the user releases a keyboard key.
Layout Occurs when the form should reposition its child controls. If your code needs to perform custom repositioning, this is the event where it should do so.
Load Occurs after the form is loaded but before it is displayed. You can perform one-time initialization tasks here.
LostFocus Occurs when the focus moves out of the form.
MouseClick Occurs when the user clicks the form. You should consider the Click event to be on a logically higher level than MouseClick. For example, the Click event may be triggered by actions other than an actual mouse click (such as the user pressing the Enter key).
MouseDoubleClick Occurs when the user double-clicks the form. You should consider the DoubleClick event to be on a logically higher level than MouseDoubleClick.
MouseDown Occurs when the user presses the mouse down over the form. Also see the Capture property.
MouseEnter Occurs when the mouse first moves so it is over the form. If the mouse moves over one of the form’s controls, that counts as leaving the form, so when it moves back over an unoccupied part of the form, it raises a MouseEnter event.
MouseHover Occurs when the mouse remains stationary over the form for a while. This event is raised once when the mouse first hovers and then is not raised again until the mouse leaves the form and returns. Note that the mouse moving over one of the form’s controls counts as leaving.
MouseLeave Occurs when the mouse leaves the form. Note that the mouse moving over one of the form’s controls counts as leaving.
MouseMove Occurs when the mouse moves while over the form.
MouseUp Occurs when the user releases a mouse button. When the user presses a mouse button down, the form captures subsequent mouse events until the user releases the button. While the capture is in place, the form receives MouseMove events, even if the mouse is moved off of the form. It will receive a MouseHover event, even if the mouse is off of the form, if no such event has been raised since the last time the mouse moved over the form. When the user finally releases the button, the form receives a MouseUp event and then, if the mouse is no longer over the form, a MouseLeave event.
MouseWheel Occurs when the user moves the mouse wheel. The event’s e.X and e.Y parameters give the mouse’s current position. The e.Delta parameter gives the signed distance by which the wheel has been rotated. Currently, this is defined as 120 detents per notch of the wheel. (A detent is a unit of the wheel’s rotation. A notch is the amount by which the wheel rotates with a discrete click. So every time you turn the wheel 1 notch, e.Delta changes by 120 detents.) Standards dictate that you should scroll data when the accumulated delta reaches plus or minus 120 detents, and that you should then scroll the data by the number of lines given by SystemInformation.MouseWheelScrollLines (currently this is 3). If higher-resolution mouse wheels are added some day, a notch might send a value smaller than 120, and you could update the data more often, but you should keep the same ratio: SystemInformation.MouseWheelScrollLines lines per 120 detents.
Move Occurs when the form is moved.
Paint Occurs when part of the form must be redrawn. You can use the e.ClipRectangle parameter to see what area needs to be drawn. For very complicated drawings, you may be able to draw more quickly if you only draw the area indicated by e.ClipRectangle. Note also that Visual Basic clips drawings outside of this rectangle and may clip some areas inside this rectangle that do not need to be redrawn. That makes drawing faster in some cases. The idea here is that part of the form has been covered and exposed so only that part must be redrawn. If you need to adjust the drawing when the form is resized, you should invalidate the form in the Resize event handler to force a redraw of the whole form.
Resize Occurs when the form is resized.
ResizeBegin Occurs when the user starts resizing the form.
ResizeEnd Occurs when the user has finished resizing the form.
SizeChanged Occurs when the form is resized.

When focus moves into and out of a form, the sequence of events is: Activated, GotFocus, Deactivate, Validating, Validated, LostFocus.

Typically, when the user clicks the form, the sequence of events is: MouseDown, Click, MouseClick, MouseUp.

Typically, when the user double-clicks the form, the sequence of events is: MouseDown, Click, MouseClick, MouseUp, MouseDown, DoubleClick, MouseDoubleClick, MouseUp.

When code resizes the form, the sequence of events is: Resize, SizeChanged.

When the user resizes the form, the sequence of events is: ResizeBegin, Resize, SizeChanged, Resize, SizeChanged, . . ., ResizeEnd.

PROPERTY-CHANGED EVENTS

The Form class provides several events that fire when certain form properties change. The name of each of these events has the form PropertyName Changed where PropertyName is the name of the corresponding property. For example, the BackColorChanged event fires when the form’s BackColor property changes.

The following is a list of these events.

BackColorChanged MaximumSizeChanged
BackgroundImageChanged MinimumSizeChanged
ContextMenuChanged ParentChanged
CursorChanged SizeChanged
DockChanged StyleChanged
EnabledChanged SystemColorsChanged
FontChanged TextChanged
ForeColorChanged VisibleChanged
LocationChanged

The names of most of these events are self-explanatory, so they are not described here. The exception is the SystemColorsChanged event. This occurs when the system’s colors are changed either by the user or programmatically.

For example, suppose that you want the form to draw using its ForeColor property and you want that property to match the active title bar text color. Then, you could use the following code to update ForeColor when the user changed the system colors:

Private Sub Form2_SystemColorsChanged() Handles MyBase.SystemColorsChanged
    Me.ForeColor = SystemColors.ActiveCaptionText
End Sub

Note that Visual Basic invalidates the form after raising the SystemColorsChanged event, so the form immediately repaints itself using the new settings.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.218.114.244