0% found this document useful (0 votes)
81 views

Unit 2 Chapter 4 Windows Forms Copy 1

The Windows Forms chapter discusses the basic structure and properties of forms in Visual Basic .NET. Forms provide a container for controls and have common elements like a title bar, menu bar, client area, and borders. The Form class in the System.Windows.Forms namespace represents forms. Forms have numerous properties that control appearance and behavior, like BackColor, Size, and Visible. They also support standard events like Click, Closed, and KeyDown that allow code to respond to user interactions.

Uploaded by

abhijna
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
81 views

Unit 2 Chapter 4 Windows Forms Copy 1

The Windows Forms chapter discusses the basic structure and properties of forms in Visual Basic .NET. Forms provide a container for controls and have common elements like a title bar, menu bar, client area, and borders. The Form class in the System.Windows.Forms namespace represents forms. Forms have numerous properties that control appearance and behavior, like BackColor, Size, and Visible. They also support standard events like Click, Closed, and KeyDown that allow code to respond to user interactions.

Uploaded by

abhijna
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Unit 2 Chapter 4 Windows Forms

Introduction
Form is a placeholder for all controls that can be placed from toolbox. In VB.NET, the support for
Windows forms is in the System.Windows.Forms namespace and the from class is
System.Windows.Forms.Form. The Visual Basic Integrated Development Environment (IDE) shows
several aspects of forms.

At the top of the form, there is a title bar, which displays the title of the form, by default it is Form1. At
the right in the title bar there is control box that includes maximize, minimize and close buttons. Under the
title bar, it has a menu bar. If the form contains any menu, it gets displayed in the menu bar. Under the
menu bar, forms can have tool bars. The main area of the form is called client area where controls such as
Text Boxes, Command Buttons Labels etc can be placed based on the requirement. The whole form is
surrounded by a border.
The important class for Windows forms is the Form class in System.Windows.Forms namespace each
form in the namespace is an instance of that class. Classes can have members—fields (data items)
methods (built-in procedures) and properties (data items accessed through an interface based on
methods).
There are two kinds of class members for Form class. They are
 Static/Shared members (class members) which are accessed directly using the class as
classname. membername. No object is needed.
 Instance members (object members) which are accessed by using an instance of a class as
objectname.membername.
The Form class contains only one class property namely ActiveForm, which holds currently active form
for the entire application. Public object properties of Windows forms are listed below:
Public object properties Windows forms p
Property Description
AcceptButton Gets or sets the button on the form that is pressed when the user uses Enter key.
ActiveControl Gets or sets the active control (the one with the focus)
ActiveMdiChild Gets the currently active multiple document interface (MDI) child window.
AllowDrop Indicates if the form can accept data that the user drags and drops into it.
AutoScale Indicates if the form adjusts its size to fit the height of the font used on the form and
scales its controls.
AutoScroll Indicates if the form implements auto scrolling.
BackColor Gets or sets the background color for the current form.
BackgroundImage Gets or sets the background image in the form.
Bottom Gets the location of the bottom of the form.
Bounds Gets or sets the bounding rectangle for the form.
CancelButton Indicates the button control that is pressed when the user presses the ESC key.
CanFocus Indicates if the form can receive focus.
Capture Specifies if the form has captured the mouse, or captures the mouse.
ClientRectangle Returns the rectangle that represents the client area.
ClientSize Gets or sets the size of the client area.
ContainsFocus Indicates if the form or child control has the input focus.
ContextMenu Gets or sets the shortcut menu for the current form.
ControlBox Gets or sets a value indicating if a control box is displayed.
Controls Gets or sets the collection of controls contained within the form.
Cursor Gets or sets the cursor that is displayed when the user moves the mouse pointer over
the current form.
DesktopBounds Gets or sets the size and location of the form on the Windows desktop.
DesktopLocation Gets or sets the location for the form.
DialogResult Gets or sets the dialog result for the form.
Enabled Gets or sets a value indicating if the form is enabled.
Focused Indicates if he form has input focus.
ForeColor Gets or sets the foreground color of the form.
FormBorderStyle Gets or sets the border style fo the form.
Height Gets or sets the height of the form.
Icon Gets or sets the icon for the form,.
IsMdiChild Indicates if the form is an MDI child form.
IsMdiContainer Gets or sets a value indicating if the form is a container for MDI.
Left Gets or sets the x-coordinate for the left edge of the form in pixels.
Location Gets or sets the coordinates of the upper-left corner of the form relative to the
upper-left corner of its container.
MaximizeBox Gets or sets a value indicating if the maximize button is displayed in the caption bar
of the form.
MaximumSize Returns the maximum size the form can be resized to.
MdiChildren Returns an array of forms of the MDI child forms that are parented to this form.
MdiParent Gets or sets the current MDI parent form for the current form.
Menu Gets or sets the Main Menu that is displayed in the form.
MinimizeBox Gets or sets a value indicating if the minimize button is displayed in the caption bar
of the form.
MinimumSize Gets the minimum size the form can be resized to.
Modal Gets a value indicating if the current form is displayed modally.
Name Gets or sets the name of the form.
OwnedForms Gets an array of Form objects of all forms that are owned by current form.
Owner Gets or sets the form that owns the current form.
Parent Gets or sets the parent container of this form.
ParentForm Gets or sets the form that the container form is assigned to.
Right Gets the distance between the right edge of the form and the left edge of the
container.
ShowInTaskbar Gets or sets a value indicating if the form is displayed in the Windows taskbar.
Size Gets or sets the size for the form.
StartPosition Gets or sets the starting position of the form at run time.
TabStop Gets or sets a value indicating if the user can give the focus to the form using Tab
key
Tag Gets or sets the object that contains data about the form.
Text Gets or sets the text associated with the current form.
Top Gets or sets the top coordinate of the form.
TopLevel Gets or sets a value indicating if the form should be displayed as top-level window.
TopMost Gets or sets a value indicating if the form should be displayed as the topmost form
of the application.
Visible Gets or sets a value indicating if the form is visible.
Width Gets or sets the width of the form.
WindowState Gets or sets window state of the form.

Public object methods of Windows Forms


Method Description
Activate Activates the form. Gives focus to the form and makes it active.
AddOwnedForm Adds an owned form to the current form.
BringToFront Brings the form to the front of the stacking order.
Close Closes the form.
Contains Indicates if the specified control is a child of the current form.
Dispose Releases the resources used by the form.
DoDragDrop Begins a drag-and-drop operation.
Focus Gives focus to the form.
GetChildAtPoint Gets the child control that is located at the specified coordinates.
GetNextControl Gets the next control in the tab order of child controls.
Hide Hides the form.
LayoutMdi Arranges the MDI child forms within the MDI parent form.
PointToClient Finds the location of the specified screen point to client coordinates.
PointToScreen Finds the location of the specified client point to screen coordinates.
RectangleToClient Finds the location of the specified screen rectangle to client coordinates.
RectangleToScreen Finds the location of the specified client rectangle to screen coordinates.
Refresh Forces the form to repaint (redraw) itself and any child controls.
Select Selects the current form.
SetToBack Sends the form to the back of the stacking order.
SetBounds Sets the bounds of the form.
SetDesktopBounds Sets the bounds of the form in desktop coordinates.
SetDesktopLocation Sets the location of the form in desktop coordinates.
Show Makes the form display by setting the visible property to true.
ShowDialog Displays the form as a modal dialog box.

Windows forms also support events. Events allow the user something has happened to the control. For
example: when the user clicks a form, a Click event occurs.
Event Description
Activated Occurs when the form is activated in the code or by the user.
Click Occurs when the form is clicked.
Closed Occurs when the form is closed.
Closing Occurs when the form is closing.
ControlAdded Occurs when a control is added.
ControlRemoved Occurs when a control is removed.
CursorChanged Occurs when the cursor property value has changed.
Deactivate Occurs when the form loses focus and it is not active form.
DoubleClick Occurs when the form is double-clicked.
DragDrop Occurs when a drag-and-drop operation is completed.
DragEnter Occurs when an object is dragged into the bounds of the form.
DragLeave Occurs when an object has been dragged into and out of the bounds of the form.
DragOver Occurs when an object has been dragged over the bounds of the form.
Enter Occurs when a form is entered.
ForeCplorChanged Occurs when the ForeColor property value has been changed.
GotFocus Occurs when the form receives focus.
KeyDown Occurs when a key is pressed down while the form has focus.
KeyPress Occurs when a key is pressed while the form has focus.
KeyUp Occurs when a key is released while the form has focus.
Layout Occurs when a form has to lay out its child controls.
Load Occurs before a form is displayed for the first time.
LocationChanged Occurs when the Location property value has changed.
LostFocus Occurs when the form loses focus.
MdiChildActivate Occurs when an MDI child form is activated or closed within an MDI application.
MouseDown Occurs when the mouse pointer is over the form and a mouse button is pressed.
MouseEnter Occurs when the mouse pointer enters the form.
MouseHover Occurs when the mouse pointer hovers over the form.
MouseLeave Occurs when the mouse pointer leaves the form.
MouseMove Occurs when the mouse pointer is moved over the form.
MouseUp Occurs when the mouse pointer is moved over the form and a mouse button is
released.
MouseWheel Occurs when the mouse wheel moves while the form has focus.
Move Occurs when the form is moved.
Paint Occurs when the form is redrawn.
Resize Occurs when the form is resized.
SizeChanged Occurs when the Size property value has changed.
TextChanged Occurs when the Text property value has changed.

MDI Forms
There are three types of forms in Visual Basic namely standard form, MDI form and MDI child form.
Multiple Document Interface (MDI) form closely resembles standard form with a major difference—the
client area of an MDI form acts as an enclosure for other forms. MDI form is also called as a parent form
that can contain many MDI children. The third type of form in Visual Basic is MDI child form. These
types of forms appear in MDI child window.

Creating Windows Applications


When a New Project button is pressed in the start page, the following files can be created:
 WinHello.vbproj—A Visual Basic Project
 AssemblyInfo.vb—General information about an assembly, including version information.
 Form1.vb—A code file of the form.
 Form1.resx—An XML-based resource template.
 WinHello.vbproj.user—Stores project user options.
 WinHello.sln—The solution file, storing the configuration of the solution.
 bin—Directory for binary executables.
 obj—Directory for debugging binaries.

Adding Controls to Forms


In Windows, users interact with an application using controls— scroll bars, buttons, text boxes menus and
so on. A control can be added by selecting it from the tool box and dragging and dropping it on the form.
These controls can be customized by setting appropriate properties.
Handing Events
When controls are added to a form, they do not do anything when the program is executed. To make any
control work as per the user requirement, it is necessary to include appropriate code. For example, if the
user wishes to display a message in a text box when a button is clicked, the required button must be double
licked to open code designer of the form and the following code has to be included to do the needful:
Private Sub Button1_Click(ByVal Sender As System.ObjecT, _
ByVal e As System.EventArgs) Handles Button1.Click
TextBox1.Text=”Welcome to Visual Basic”
End Sub

Setting Title Bar Text


Text in the title bar can be set in two ways--at design time, just by changing the Text property of the form,
at run time using code as follows:
Private Sub Button1_Click(ByVal Sender As System.ObjecT, _
ByVal e As System.EventArgs) Handles Button1.Click
Text=”Welcome to Visual Basic”
End Sub
Adding/Removing Min/Max Buttons
Forms usually come with minimize, maximize and close buttons as a close box at the upper right. To
remove these buttons, ControlBox property of the form can be set to False. Maximize and minimize
buttons can be independently removed with MaximizeBox and MinimizeBox properties.

Setting the Border of a Form


Border style of the form can be set using FormBorderStyle property. The possible values are:
 Fixed3D—A fixed three-dimensional border.
 FixedDialog—A thick, fixed dialog-style border.
 FixedSingle—A fixed single-line border.
 FixedToolWindow—A tool window border that is not resizable.
 None—No border.
 Sizable —A resizable border.
 SizableToolWindow—A resizable tool window border

Setting Tab Order for Controls


In Visual Basic, controls can be made accessible to the keyboard by setting their tab order. The user can
move from one control to another, highlighting the currently selected control using the Tab key. To set tab
order for controls in a form, following steps are to be followed:
1. The control whose tab order is to be changed must be selected.
2. The TabStop property of the control must be set to True. If this property is false, user cannot reach
the control using the Tab key.
3. The position of the control in the tab order can be set using TabIndex property. The first control in
the tab order will have TabIndex 0, the next 1 and so on.
4. When the program is executed, the first control with TabIndex 0 will be highlighted; when Tab
key is pressed, the focus moves to the second control in the tab order and so on.

Setting Initial Position for the Form


Initial position for the form can be set by using StartPosition property. The possible values are:
 CenterParent—The form is centered within the bounds of its parent form.
 CenterScreen—The form is centered on the current display and has dimensions specified by its
size.
 Manual—The location and Size properties of the form will determine the starting position.
 WindowsDefaultBounds—The form is positioned at the Windows default location and has the
bounds determined by Windows default.
 WindowsDefaultLocation-- The form is positioned at the Windows default location and has the
dimensions specified by its size.
Moving and Sizing Forms and Controls in Code
Size property and Location properties of controls can be user to resize and move controls in code.
SetBounds method can also be used to move forms and controls. The Size property is to be set to new Size
object and the Location property to new Point object. Size and Point objects are measured in pixels as:
Size(x_dimension, y_dimension)and Point(x_location, y_location).
Example:
Private Sub Button1_Click(ByVal Sender As System.ObjecT, _
ByVal e As System.EventArgs) Handles Button1.Click
Size = New Size(100,100)
Location = New Point(0, 0)
Button1.Size= New Size(100,50)
Button1.Location= New Point(0,0)
End Sub

This will change the size and location of both form and a button in the form when Button1 is clicked.
SetBounds can also be used to do the same thing:
Overloads Public Sub SetBounds(ByVal x As Integer, ByVal y As Integer, _
ByVal width As Integer, ByVal height As Integer, _
ByVal specified As BoundsSpecified)
 x—The new Left property value of the control
 y—The new Right property value of the control
 width—The new Width property value of the control
 height—The new Height property value of the control

Overloads keyword indicates that SetBounds is overloaded, which means, there is more than one form of
this method. BoundsSpecified is an enumeration which can have one of the following values:
 All—Specifies that both Location and Size property values are indicated.
 Height—Specifies that the height of the control is indicated.
 Location—Specifies that both x and y coordinates of the control are indicated.
 None—Specifies that no bounds are indicated.
 Size—Specifies both Width and Height property values of the control are indicated.
 Width—Specifies that the width of the control is indicated.
 X—Specifies that the left edge of the control is indicated.
 Y—Specifies that the right edge of the control is indicated.

Example:
Private Sub Button1_Click(ByVal Sender As System.ObjecT, _
ByVal e As System.EventArgs) Handles Button1.Click
SetBounds(0,0,100,100)
Button1.SetBounds(0,0,100,50)
End Sub

Showing and Hiding Controls and Forms


A control can be shown on the form by setting the Visible property of the same to True. Visible is equal to
False will hide the control.
Private Sub Button1_Click(ByVal Sender As System.ObjecT, _
ByVal e As System.EventArgs) Handles Button1.Click
Button1.Visible=False
End Sub
Show and Hide methods of controls and forms can also be used to show and hide them. For example
Private Sub Button1_Click(ByVal Sender As System.ObjecT, _
ByVal e As System.EventArgs) Handles Button1.Click
Form2.Hide()
Form3.Show()
End Sub
Using the MsgBox Function
MsgBox can be used to display messages and accept inputs from the user. It displays a message and some
buttons. The syntax of MsgBox is :
Public Function MsgBox(Prompt As Object [, Buttons As MsgBox Style =
MsgBoxStyle.OKOnly] [, Title As Object = Nothing]) As MsgBoxResultArguments
 Prompt—A string expression displayed as the message. The maximum length is about 1024
characters (depending on the width of characters used).
 Buttons—The sum of values specifying the number and type of buttons to display, the icon style to
use, the identity of the default button and the modality of the message box. The default value is
zero.
 Title—String expression displayed in the title bar of the dialog box, if omitted, title of the
application is placed in the title bar.

MsgBox Constants
Constant Value Description
OKOnly 0 Shows OK button only
OKCancel 1 Shows OK and Cancel buttons.
AbortRetryIgnore 2 Shows Abort, Retry and Ignore buttons.
YesNoCancel 3 Shows Yes, No and Cancel buttons.
YesNo 4 Shows Yes and No buttons.
RetryCancel 5 Shows Retry and Cancel buttons.
Critical 16 Shows Critical Message icon.
Question 32 Shows Warning Query icon.
Exclamation 48 Shows Warning Message icon.
Information 64 Shows Information Message icon.
DefaultButton1 0 First button is default.
DefaultButton2 256 Second button is default.
DefaultButton3 512 Third button is default.
ApplicationModal 0 User must respond to the message box before continuing work in the
current application.
SystemModal 4096 All applications are unavailable until the user dismisses the message
box.
MsgBoxForeground 65536 Specifies the message box window as the foreground window.
MsgBoxRight 524288 Text will be right-aligned.
MsgBoxRTLReading 1048576 Specifies text to appear as right-to-left on RTL systems such as Hebrew
and Arabic
This function returns a value from the MsgBoxResult enumeration. The possible values are:
OK, Cancel, Abort, Retry, Ignore, Yes or No
Private Sub Button1_Click(ByVal Sender As System.ObjecT, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim Result As Integer
Result=MsgBox(This is Message Box”, MsgBoxStyle.OKCancel+_
MsgBoxStyle.Information+ MsgBoxStyle.SystemModal, “Message Box”)
If (Result = MsgBoxResult.OK) Then
TextBox1.Text =”You clicked OK”
End If
End Sub
This example will display a message box with message “This is Message Box” that contains two buttons
OK and Cancel. When OK button is pressed, TextBox1 will contain the text “You clicked OK”

Using the MessageBox.Show Method


Show method of MessageBox class can also be used to display message boxes. This method has several
forms; one of them is given below:
Overloads Public Shared Function Show(ByVal text As String , ByVal y Caption As String, _
ByVal buttons As MessageBoxButtons, ByVal icon As MessageBoxIcon, ByVal_
DefaultButton As MessageBoxDefaultButton, ByVal option As MessageBoxOptions) As DialogResult
 text—The text to be displayed in the message box.
 caption—The text to be displayed in the title bar of the message box.
 buttons—One of the MessageBoxButton enumeration values that specifies which buttons to be
displayed in the message box.
 icon—One of the MessageBoxIcon enumeration values that specifies which icon to display in the
message box.
 defaultbutton—One of the MesssageBoxDefaultButton enumeration values that specifies which is
the default button for the message box.
 options—One of the MessageBoxOptions enumeration values that specifies which display and
association options will be used for the message box.

The possible values for MessageBoxButton enumeration are:


 AbortRetryIgnore—The message box will display Abort, Retry and Ignore buttons.
 OK—The message box will display OK button.
 OKCancel—The message box will display OK and Cancel buttons.
 RetryCancel—The message box will display Retry and Cancel buttons.
 YesNo—The message box will display Yes and No buttons.
 YesNoCancle—The message box will display Yes No and Cancel buttons

The possible values for the MessageBoxIcon enumeration are:


 Asterisk—Shows an icon displaying a lowercase letter i in a circle.
 Error—Shows an icon displaying a white X in a circle with a red background.
 Exclamation—Shows an exclamation in a triangle with a yellow background.
 Hand—Shows an icon displaying a white X in a circle with a red background.
 Information—Shows an icon displaying a lowercase letter i in a circle.
 None—Shows no icon.
 Question—Shows an icon displaying a question mark in a circle.
 Stop—Shows an icon displaying a white X in a circle with a red background.
 Warning—Shows an exclamation in a triangle with a yellow background.

The values for MessageBoxDefaultButton enumeration are:


 Button1—Makes the first button on the message box the default button.
 Button2—Makes the second button on the message box the default button.
 Button3—Makes the third button on the message box the default button.
The values for MessageBoxOptions enumeration are:
 DefaultDeskTopOnly—Displays the message box on the active desktop.
 RightAlign—The message box text is right-aligned.
 RtlReading—The text in the message box will be displayed with right to left reading order.
 ServiceNotification—The message box is displayed on the active desktop when the service makes
a call notifying the user of an event. The function displays a message box on the current active
desktop even if there is no user logged on to the computer.

The result of the Show method is a value from the DialogResult enumeration, showing the button clicked
by the user.
 Abort—Returns Abort.  None—Returns nothing.
 Cancel—Returns Cancel.  OK—Returns OK.
 Ignore—Returns Ignore.  Retry—Returns Retry.
 No—Returns No.  Yes—Returns Yes
Example:
Private Sub Button1_Click(ByVal Sender As System.Object, _
ByVal e As Event.Args) Handles Butt1.Click
Dim Result As Integer
Result=MessageBox.Show(“This is a message Box”, “Message Box”, _
MessageBpxButtons.OKCancel, MessageBoxIcon.Information, _
MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly)
If(Result=DialogResult.OK) Then
TextBox1.Text=”You Clicked OK”
End If
End Sub

Using the InputBox Function


InputBox function is used to get a string of txt from the user. The syntax for this function is
Public Function InputBox(Prompt As String [, Title As _
String = “” [, DefaultResponse As String= “” [, _
XPos As Integer = -1 [, YPos As Integer = -1]]]]) As String
 Prompt—A string expression displayed as message in the dialog box. The maximum length is
about 1024 characters depending on the width of characters used.
 Title—String expression displayed in the title bar of the dialog box. If title is omitted, name of the
application is placed in the title bar.
 DefaultResponse—A string expression displayed in the text box as default response if no other
input is provided. If DefaultResponse is omitted, displayed text box will be empty.
 XPos—The distance in pixels of the left edge of th dialog box from the left edge of the screen. If
XPos is omitted, the dialog box will be centered horizontally.
 YPos—The distance in pixels of the upper edge of the dialog box from the top of the screen. If
YPos is omitted, the dialog boxis positioned vertically about one third of the way down the screen.
Example:
Private Sub Button1_Click(ByVal Sender As System.Object, _
ByVal e As Event.Args) Handles Butt1.Click
Dim Result As String
Resutlt=InputBo(“Enter the text”
Text1.Text=Result
End Sub

When user enters text and click OK button on the InputBox, the InoutBox function resturns that text and
displays it in Text1.

Working with Multiple Forms


Visual Basic .NET allows multiple forms to be handled effectively. To add another form to the current
project, /add Windows Form option must be selected from the Project menu.

You might also like