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 9, "Using Windows FormsControls," 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

AcceptButton

Determines the button that clicks when the user presses the Enter key. This button basically gives the form a default action. Most forms used as dialog boxes should have an Accept button and a Cancel button (see the CancelButton property described shortly). This makes the form more accessible to the visually impaired and is more efficient for users who prefer to use the keyboard.

ActiveControl

Gets the form's currently active control.

ActiveForm

Gets the application's currently active form. If an MDI (Multiple Document Interface) child form is active, this returns the active form's MDI parent.

ActiveMdiChild

Gets the MDI parent form's currently active MDI child form.

AllowDrop

Determines whether the form processes drag-and-drop events. See Chapter 23, "Drag and Drop, and the Clipboard," for more information on drag-and-drop tasks.

Anchor

Determines which edges of the form are anchored to the edges of its container. This lets MDI child forms resize with their MDI parents.

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 even 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). For example, the following statement makes the form just big enough to display the txtNotes control within the client area:

Me.ClientSize = New Size(
    lblNotes.Left + lblNotes.Width,
    lblNotes.Top + lblNotes.Height)

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 the controls on the form. This includes only the controls contained directly within the form, and not controls contained within other controls. For example, if a form contains a GroupBox that holds several TextBox controls, only the GroupBox is listed in the form's Controls collection. You would need to search the GroupBox control's Controls collection to find the TextBox controls.

Cursor

Determines the cursor displayed by the mouse when it is over the form.

DesktopBounds

Determines the form's location and size as a Rectangle.

DesktopLocation

Determines the form's location 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. Many of the API functions that are necessary in Visual Basic 6 are no longer needed in Visual Basic .NET because their functions have been incorporated into the .NET Framework, but there are still occasions when the form's handle is useful.

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 × 16 pixels and 32 × 32 pixels, so different displays can use an image with the correct size without resizing.

IsMdiChild

Returns True if the form is an MDI child form. To make an MDI application, set IsMdiContainer = True for the MDI parent form. Then display a child form, as shown in the following code. In the child form, IsMdiChild will return True.

Dim child_form As New MyChildForm ()
child_form.MdiParent = MdiParentForm
child_form.Show

IsMdiContainer

Returns True if the form is an MDI parent form. See the description of IsMdiChild for more information.

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. For example, the following statement in a KeyDown event handler would close the form if the user presses Escape, no matter what control has the focus:

If e.Keys = Keys.Escape Then Me.Close

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.

MdiChildren

Returns an array of forms that are this form's MDI children.

MdiParent

Gets or sets the form's MDI parent form.

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).

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. For more information on regions, see Chapter 31, "Brushes, Pens, and Paths."

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 runtime. 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 Windows default position and size).

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 default form and control 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. For example, the following code draws a circle when the user presses a button:

Private Sub Button1_Click(

 ByVal sender As System.Object,

 ByVal e As System.EventArgs) _

 Handles Button1.Click

    Dim gr As Graphics =

        Me.CreateGraphics()

    gr.FillEllipse(Brushes.Orange,

        10, 10, 210, 220)

    gr.DrawEllipse(Pens.Red,

        10, 10, 210, 220)

End Sub

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.

DoDragDrop

Begins a drag-and-drop operation. For more information on drag and drop, see Chapter 23.

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.

LayoutMdi

If this form is an MDI parent form, arranges its MDI child forms. This method can take the parameters ArrangeIcons, Cascade, TileHorizontal, and TileVertical. Typically, this command is used in a menu titled Window.

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.

ResetBackColor

Resets the form's BackColor property to its default value (Control). This change is adopted by any controls on the form that do not have their BackColor properties explicitly set.

ResetCursor

Resets the form's Cursor property to its default value (Default). This change is adopted by any controls on the form that do not have their Cursor properties explicitly set.

ResetFont

Resets the form's Font property to its default value (8-point regular Microsoft Sans Serif). This change is adopted by any controls on the form that do not have their Font properties explicitly set.

ResetForeColor

Resets the form's ForeColor property to its default value (ControlText). This change is adopted by any controls on the form that do not have their ForeColor properties explicitly set.

ResetText

Resets the form's Text property to its default value (an empty string).

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 notremove 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. 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.

ControlAdded

Occurs when a new control is added to the form.

ControlRemoved

Occurs when a control is removed from 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.

DragDrop

Occurs when the user drops data onto the form. The form should process the data in an appropriate way. See Chapter 23 for more information on drag-and-drop operations.

DragEnter

Occurs when a drag-and-drop operation moves over the form. The form should indicate what drag operations it will allow and optionally display a visible indication that the drag is over it. Refer to Chapter 23 for more information on drag-and-drop operations.

DragLeave

Occurs when a drag-and-drop operation leaves the form. If the form is displaying a visible indicator of the pending drop, it should remove that indicator now. See Chapter 23 for more information on drag-and-drop operations.

DragOver

Occurs repeatedly as long as a drag-and-drop operation is being performed over the form. The form can use this event to display a more complex visible indicator of the pending drop. For example, it might show where on the form the data will be dropped or it might highlight the area on the form under the mouse. See Chapter 23 for more information on drag-and-drop operations.

FormClosed

Occurs when the form is closed. The program can still access the form's properties, methods, and controls, but it is 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 even handler's e.Cancel parameter to True.

GiveFeedback

Occurs when a drag moves over a valid drop target. The source can take action to indicate the type of drop allowed. For example, it might change the drag cursor displayed. See Chapter 23 for more information on drag-and-drop operations.

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.

MdiChildActivate

Occurs when an MDI child form contained in this MDI parent form is activated or closed. This activation only applies to the MDI children within this form. For example, setting focus to a different form or application and then back to the MDI child does not raise this event, but switching back and forth between two MDI children does. This event basically occurs when the MDI parent's active MDI child changes. You can catch the event to update the MDI parent's menus or perform other actions when the active child changes.

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 the mouse button. When the user presses a mouse button down, the form will capture 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 moving 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.

QueryContinueDrag

Occurs during a drag-and-drop operation (with this form as the drag source) when the keyboard or mouse button state has changed. The form can decide to continue the drag, cancel the drag, or drop the data immediately. See Chapter 23 for more information on drag-and-drop operations.

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

MaximumSizeShanged

BackgroundImageChanged

MinimumSizeChanged

ContextMenuChanged

ParentChanged

CursorChanged

SizeChanged

DockChanged

StyleChanged

EnabledChanged

SystemColorsChanged

FontChanged

TextChanged

ForeColorChanged

VisibleChanged

LocationChanged

 

The names of most of these controls 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(ByVal sender As Object,
 ByVal e As System.EventArgs) 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
3.15.186.248