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

Chapter 4 AP

Uploaded by

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

Chapter 4 AP

Uploaded by

mr.arjunb27
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

Windows Forms in

Visual Basic 2010


If you need an Information on: See page:

Explonng Windows Forms 116


120
Creating Window Forms Application
Adding Controls to Windows Forms
----- ----- ----- ----- ----- 121

Disabling and Enabling Windows Forms 122


Changing the Title of Windows Forms 123

Setting the Border of Windows Forms 124

Displaying and Hiding the Maximize, Minimize, and Close Buttons of Windows Forms 125
----- ---
Specifying the Initial Position of Windows Forms
Creating Multiform Windows Applications 127
---------------------------------,,..............,,.--,- 130
Displaying Messages
Using Windows Forms to Create Dialog Boxes 134

Creating Owned Windows Forms 136

Creating Always-On-Top Windows Forms 137

Performing Some Common Operations on Controls 13&

Handling Common Events for Window Forms and Controls 146

Specifying the Mouse Cursor for Windows Forms and Controls a


Chapter4 . erf ce for building Windows client applicati Windows Forms In Visual Basic 2010
hiclll u.<er int a ons th
\Oldow,; forDl IS a grap their e,.ecubon. It is the name given _to the Graphical Use at use the
\ Runtune (CLR) for -rT Framework. )ou can create Windows Form appJ r lnt\'rfac o!
Jn Figure 4 1, the htle_ the form , Form!, it displays on the form title b.ir. Al the lop-nght comer of the form •s
Unguage of ~ t \c, •cations 111 e (CL) the control box contammg the Minimize, Maximize, and Cl~e buttons The main area of a form 1s where vou
o:,ns11tuies a part any ~ can d rag and drop the controls, such as Buttons, and TextBoxes. In general, the Visual Ba<1c code work:- with
____......i b) CIJt F _< programmers had to perform the difficult
controls m the mam area, even though 11 1s itself a wmdow. Finally, a border ~urrounds the entire form Then'
""l't"'"-- of\\ indows ow~, , 'tiall th and c
Pnor to 1hr mttodudlOl1 . ol code 111 a proJect, lni y, e programmers chi fl . urn~ are se,·eral ty pes of borders that you can use, which are discussed later in the chapter
1
manu,al]\ wnting thou.sands of ~ , (MFO library for coding their projects. Howevere!\-~relied on M ~I
n,e most important class of a Windows Form is the Form class, which rt."-ides m the System Windows Forms
C+.ta<i!d M.iaO-oft fow,d.Jbon ded an easi· and ideal wav to crea te a pplications. Winct' C Was SOo •er
, "tuch pro\1 • • . 01vs F n,~ , namespace. Each form in this namespace is an instance (that is, an object) of the Form class. Objects are instance
t,\\\indol\<Fortre ch"Button LabeJ,andTextBox, tocrea teWmdowsap 1. 0 rtnsai1 .'~ of classes, such as an integer variable is an instance of the Integer type. (You can think of a clas, as a I) pe from
t ofcontro" I ,u = ' . P •catio 0\\-1
add difkren ll-pei lica _ allo" q•ou 10 design mulbple forms to perform Various t ns quJckll 'lii ,~here objects are created.) You already know that classes can ha\e member;, ,uch as fields (data 1tem,J
A \\rind"", Fonns ap~:perties ·and e\'ents. For ~pie, you can create a Windo,~~;5 by Using di// methods (built-in procedures), and properties (data items accessed through an interface based on methods)
control> b) -~~
acttpl 1hr u.'<?f mput uvm
! form and dispLw the details on another form using different nns applica ~
·
0

set of con ~
n,ere are two kinds of class members. The first are members inherent to the class itself (acce55ed through the
_ ;plains how to work with Windows Forms. You also learn to perform tasks lrols class), such as Form.Activeform or just ActiveForm. These members, called stahc shared, or class member;, do
In~~~ and~~ buttons of forms, di.sabling and enabling Windows F such as dispJa not need objects to access the members of the class. The second kind of class members are called U\Stance or
:ie of /wind""' Form. setting the border of a \•tmdows Form, ~ d handling multiple fo:;:s,changing ~
· In this ch.
1
object members built into_objects, such as MyForml.BackColor.The MyForml IS an instance of the Form clas,,,
where you do need an obiect to access the class members. The basic difference between a class member and an
al, de;a)be; the u,e of the MsgBox function and Message8ox.Sho1, method to create mes
~~ hol\ to create the Always-On-Top Windows as well as the Owned Windows sage boxes_yoU l-'ll fo object member is that to use a class member, you do not need an object of that class, but with object members,
chapter de,ail,es some of the common operations using controls such ~ a B~tton, Label, ~~>..~ addition,: \'OU need the following members:

Finalh·, the chapter descnbes common mouse and keyboard events, mcludmg how to SPE'Cifl-Bo~ and 50 ~ Static/Shared members-Accesses directly using the class, such as class name.member name
type ·for controls and forms. • lllo11.1e ~ 0 Instance members -Accesses by using an instance of a class (an object), such as object name.member name
• , 'Jq:m th a b-ief discussion of \\"mdows Fonns. We prefer the terms such as class members and object members because these clarify what type of members the)
are, but Microsoft Developer Neh,•ork (MSDN) often uses the terms Static (Shared) members and ln-'tance
Exploring Windows Forms members .
•• ;. mdo,, Form is a graphical user in~ce on which you ~lay information, either textual or The Form class has only one class properly, ActiveForm, which holds the currently ach\·e form for the entire
user _or_= the mput from the user m the form of text or rmages by using variety of contr:Phical.m1 application. If you want to determine which window is active, use the ActiveForm p;operty. However, the Form
applicllbons are del'eloped b) adding controls to forms and b1 handling events such · l\md°"' class does have many object properties. Some of these object properties are public, some pnvate to the object.
clicks and ~ on. The support for Windows Forms -in Visual Basic , ?QlQ a~ mouse dicks bu!!:r and some protected (that is, only accessible to objects of the Form class or objects of classes derived from Form).
S),tem.\\"mdows.Forms namespace and for the Form class in the System.Windo:i.s.Fo~j::ded in lie \\'hen working with forms, one usually uses the public object members (that is, public properti~. methods. and
The Fonn class itself IS based on the Control class, wluch means that the forms share man . h ~ events of Form objects). Note that, as is usual with properties and methods m Visual Baste, not all these
methods of the Control class. The inhentance hierarchy of the Form class is: ) t e properties a.'\l properties and methods will be available at the time you are designing your code; only some of them will be
syst~.ObJect available at runtime. Table 4.1 lists noteworthy public properties of the Form class:
Svsters.~arshal ByRefobj ect
syste~. componentMode l . component
---
Ta ble 4.1: Noteworthy Public Properties of the Form Class
,. ___ a,.:.;...,;,
system.windows. Forms. contro 1 Property
System . Windows. Forms . Scro 11 abl econtro l A, ceptButton Obtains or sets the button on the form when th-, user I'"'"-'"" the Enter ke1
SyS t em. Windows• Forms. contai nercontro l Ac tiveFonn Retrieves the presently active form of the application
Figure 4.1 shows a \\"mdows Fo . ti d . SyS!em •Windows. Forms. Form I
rm m te es1gn mode: Ac tiveMdiChild Retrieves the presently active multiple document interlacl' (l',IDI) child wmd,,"
Al lowTransparency Obtains or sets the value to adjust the opacit, of the lorm
r--
Au toScaleBaseSize I Obtains or sets the base size used for auto scaling the tonn
Au toScroll Indicates whether the form implements auto scrolhng
Au toSize Resizes the form as per the settings of the AutioSize!l.lode prop,,rt\
Au toSizeMode I Gets or sets the mode to make changes m the sizl' of the lorm automaticall)
Au to Validate Obtains or sets the value that points whethcr the control, will be ,alidaled
automatically when their focus is changed

BackColor Obtains or sets the form background color


CancelButton I Obtains or sets tl1e Button control that is clicked when the user presses the ESC key
Cli entSize Obtains or sets the size of the mam area of Fom1
Co ntrolBox Retril!,·e~ or sets a Vlllu~ points wheth~r a conlrol b(,, i~ d1~pl,1, ._.Jon the forms caphon
116 Figure 4.1: Displaying a F --- bar

orrn Designer In Visual Studio 201 O


Des ktopBounds
--- Retrie,·e, or sets the size anrl loc,11ion of the form on the Windo\\ s dc<~1<1p

117
---
l"baf:JW' - - - - - - - - - - - - - - - - -
---------- --- Windows Forms In Visual Basic 2010
i ~ 4.1: N ~ Y Public PR>perties of the Form Cius
~ .....,,,_ Description
Rttn..,~ or~ th.: k,,bl.m ,'11 lh.- £,.,m, ,,n lh.! \\ mJ,,,,-~ J.,--.\..1,,p
foble 4.1: Noteworthy Public Properties of the Form Class -
proper1Y - - - - - - - - - . Description -~-- ----- ----- ---!
t n--,\llJt{...X.a!'>.'C!
Obt,,in., or <els --:;-a-::va:i:1u::::,,-;;,h;:-::-,7:1,:-:l,----- :-~--~ ------
f ~~\<~ R-T-- ,ir -.rt-.. !ht- '-'m<' "1th.: ,iYl,,g n.,ult P"'~rtl f..,r t~ form when r,,pLe1e 1 ----- level window. 1 ---J
• , c crmmcs whrlh,•r th,• form <h,,uld t... d1,pl.,~rJ ,1511 t,1p-
a, m,.'1.11 Jw..~ t,..,, it ts d i s ~
f ,\l
i r-.~~11: - C'~,,r-ct--th ef..'ltn, h.'l<\l,,-r"hle
- Obtains ,u sets •' value lh,,t d,•l<·rmon,>s whether th,• r,,rm ,h.,ulll ht• di<plawd
topmost !om, of the applic,,hon a, th:-

l' t..""C!l,

l,\ti.'1md
IC\ Retno.-.'°' or ,.._-t,. the , alue l''tnts "h.!tht?r the Help button sh,,uld ap~r
(Urti,xl oo,
~ ~ --& .ll\ "-'-'a k-.r th.! fom,
Retrir\-es ,-.c x--t, .& , alue lNt l''tnt:;. ii the tom, is an~ IOI child fom,
in the form-;--
s

-- __ __
_ _ _""T'"_R_et ~sets the co~senti ng the transp,irenlare.L
< of the form
..._:~::::1r sets a v,,luc that dctcrmmc whether J window 1s norm.,I. mm1ml.U"d, <'r

T ble 4 2 lists noteworthy public methods of the Form class:


ls.\L"Cmtalntt L',t,uin,. 01 -...-t-- .& , .&lue th.It p('lllts if the iorm i.< a container for MDI child
forms - ,1

~\\ind- ..-

"- Pre,.-....
ON.ain,.

R - '" -
a \"alue tNI Jct.:mune-_ whether t~ h:lrm will use all the windows und
mrat e,-mts w,th..,ut am re-tnction use-;-

,. ,. alue lh.lt determines whether the fom, will receive ull the \..ey events
-~
fable 4.2: Noteworthy Public Methods of th~ a s s

t,1ethod
~vate
- Associated Function
Activates the form by giving it focus
t,,..fore an l!'\-ent i< ~~ roan act,ve control
LLOID\
!\wn..\kn11~ p
~ o r ~ the kicallon ot the torm
Retrir\~ or~ the pnmm menu cont.uner for the !om,
- ·

--
-;,;iciownedForm
close
LayoutMdi
Adds an owned form to the parent form
O oses lhe form
Arranges MDI child forms within the MDI pi!renl form
... n, ONam.< ,,r ~ a ,.tlue th.\t Jcrermin,"' if the t.la>.imize b~ispla RemoveOwnedForm
yed in the Removes the owned form from the parent form
capb,-.n bar ol the torm
~~
setoesktopB ounds Sets lhe bounds of the form in desktop coordimtes
Obtains the ,-a!ue ro determine the ma,imum size of the fom,
M~Qw.in.,n
setDesktop Location Sets the location of the fom, in desktop coordinates
Rl"tne\-e- .ll\ arn, ot \IDI child forms p.,.rented to a rorm
Md:?lmrt ShOwDialog Displays the form as a modal dialog box
ONuns or ,-et,. the current MDI parent h:lrm of the form
\km, ToString Gets a siring representing the current instance of the form
Reine\ es or sets the main menu that is displayed in the form
ValidateChi ldren Validates all selected child controls in the form
!'.~\\mu R.-tne\ es the merged menu for the form
M:=ruzrlla>. Obtam., ,,r ~the value that Jetem,ines whether the Minimize button is displayed in Table 4 3 lists noteworthy public events of the Form class:

>-umnwnS.tt
Mod.ii
\'.)p,l,."11\
the capt,on bar of the form
RNI1e\.,,. the mimmum size the rorm can be resized to
Retne, es a , alue that determines if the torm is displayed modally
Obtam., or sets the opacil)· level oi the form
- Table 4.3: Noteworthy Public Events of the Form Class
Event
Activated
I OescrlpUon
Raises when you activate the form through the code
Closed Raises when the form is closed
OwnedFon:ns Rmie, cs an array of Form objl!Cls of all forms owned by the parent form
Closing Raises when the form is closing
0..-ner Retneve,. or -.et.s the p.,.renl form that owns the form
Deactivate Raises when the form loses focus
Right Tol..rilLl\'lllll Ok-tam, or ,...>t,, the ,·alue that determmes whether the right-to-left placement is-----
turned FormClosed Raises after the closing the form
on
Show Iron FormClosing Raises before closing the form
RetnE'\ e,. or ""'' the value that determines whether an icon (picture representing
the HelpButtonC licked Raises when you click the Help button
form on the ta,l..bar) "display,-d m the caption bar of the form
<;ho,,, lnTcl bar Ql,tam, or ,,.,t, a value that determines whether the form is displayed InputLanguageChange d Raises when you have changed the input language of the form
in the Windows
Ta,l..bar lnputLanguageChang i ng Raises when the user is trying to change the input language of the lorm
',at- Rmie,,..,, <'r :.els the Mze of the lorm Load Raises before a form is displayed for the first lime
~eGnf6t)le Obtams or set> the style of the siw grip to be displayed in the lower-right Raises when you have changed the value for the ~x i mixedBounds propcrtv
comer of the MaxmizedBoundsChanged
form
~aximumSiz eChanged Raises when you have changed the value for the Max1mumSi :e property
t,wtl\.'!Slbon .
Rctne\ cs or sets the ,tartmg position of the form al run lime Raises when an MDI child form is activalt!d or closed withm an MDI app~cahon
~diChildAc ti va te
Tablndc, Rf'tne,es or ,eb the tab order for the controls in the form
Tal:6top Retri,'\ t!S or ""-> a value that dekrmmes if the user can give focus to the
- ~uComple te Raises when the menu of the form loses focus
form by using ~OUStart Raises when the menu of. form receives focus
thc.-Tab l..,•v .
T.-xt ~nimumsi zeChanged Raises when you have chliigcd lhe va\ue of the Max lmums1ze propcrt)
Retne, ,~ ,,r ><:ls the tc,1 associatt!d with the form
~izeBegi. n Raise5 when you tryipg tJ resize the form
~SizeEnd ,. f wng the form
.,_ R~ses '''!~n_YOU :_~r~ rt>s. -
118 119
Rn1S(.'Swht•ntlwPigh ~ L ftla~ul p~pt•rtvchong<'•
Ra,...,_" h<'n th,• fom, ",hspl,w,-d l<>r th,• l11-..1 tmw
-------11--R-a,,-,,es-"~h-rn~th,•, alu~ <'I lhl' h~<'f'Crly ch,,ng<', ·--
',_
' I ' -....
<i-
ii) ....
l!l•-

.~-
'lllu ,in· TI<'" tamihnr '"th the note" orlh\ properh_es, methods.and events of Windows Form. Now you learn to c "-W.w.t.
~ ( ..0-,
,realt' ,1 \\'mJuws Form, apphcati,,n and scl tb vanous propcrhes. ) I ,........

Creating Window Forms Application ~ °""°""'..


O..a..1

\\ mdows Forms 1 re one ol the important forms that are available in Visual Basic ~010. You can create variety of
apphcatton u,mg tht"-1.' tom,,. \',mou, controls can be added lo make th_e ,1pphc,1ho~ more functiona l and user
fnendh '\ ou can ea,il) create a\\ mdows Form application by undertakmg the followmg steps:
l Sdect F1le ➔ Ncw ➔ Pro1ect The New Project dialog box appears.
2 Sdl'CI \ i,ual Basic ➔ Windows option from the Installed Templates pane and then select Windows Fornis Figure 4.3: Designing a New Windows Appllcatlon
Application opllon from the middle pane. Whenever you create a ne': W~dows Form application or project, certam files and directories are created as
Enter a name for vour application in Name text box. In our case, we entered FirstProject (also available in well. In our case, the fo llowmg files and directories are created with the First Project application:
th,· CD-ROM). □ My Project· vbproj - Opens the Project Designer to access the project properties, setllngs, and resources
4. Enter 3 location for the application, for example D:\BB_.NET Programming 4.0\ Vil
□ Assemblyinfo · vb - Contains general information such as the assembly and version of the application
Scctton\Chapters\Applications\Chapter_4\, in the Location drop down box by using the Browse button,
□ Forml. vb- Specifies a file containing the code of a form
Click th.: OK button. The FirstPro1ect application is created, as shown in Figure 4.2:
o Resources . resx- Refers an XML-based resource template
-""""'
FfF
o FirstProj ect. sln - Refers the solution file of the application, storing the solution's configurallon
o bin-Specifies the directory for binary executables
o Obj -Specifies the directory for debugging binaries
_;, ...,.~ Visual Basic 2010 crea tes all these files and directories automatically. Let's now add some controls to th~ Formlof
~ C_.Appk,r.a
the FirstProject application. ·

I ~ Cwt.Iran
Adding Controls to Windows Forms
5;;~waa-..~ You can add many useful controls in a Windows application, such as scroll bars, buttons, text boxes. and menu,,,
which users generally use to interact with the application. In Visual Basic 2010, you use the Toolbox to add
controls to a form. Let's now add a Button control and a TextBox control by just dragging the controls !Tom the
Toolbox to Forml of the FirstProject application, as shown in Figure 4.4:

..,_
:.:3 "-""-fWiof
~ ,_,
:J-
0-
fj ldoT•._
11a.-
......
,_
,;
Figure 4.2: New Project Dialog Box
The I 1rstProJl'Ct appltcation is created, as shown in Figure 4.3:
"ts.,..wie. . . .
[II -

➔· .,-
L- • .sq,
--·
:::...,~
'-bi... '-
11,-
,,,_
~ ~:,..
..---------
~~.-u::i

Figure 4.4: Adding Controls to a Form


120 121
- - - - - - - - - - - - - - - - - - - ~ - Windows Forms In Visual Basic 2010
Let< create a Window< Forms apphc.ition. n,1mcd D1s.iblcE bl' , - - ---
dJ .i Button control to Forml .ind change its T t n,, l \,', mdow Form (,ilso ,1va1lable In th. CD-ROM)
A , -.
f1gufl?-t /, e, property lo the Click Me lo D1s.1ble the Form• a hown en
-~....,-~

·--
,~-...
,,.,_,._
@-
El""-

,.~--
G-..a.
ii C.0.0..0,

---.....
,le-

..,
lil--
"-'--
~ o,ur-,._u,

'l o..c-
0 .,,_,.

Figure 4.7: Displaying the Design View of the DisableEnableWlndowsForm ~ r :


Perform the following steps to disable the \Vmdows Form,.
I. Add the.' following code snippet to the Click l?\'ent of the Buttonl ,-ootrol to d.."JNe Forni.I ll5-
Pri va Lcsub ButtonLCl_ick(Byval sender A.s system.ObjKt, By\! il e '-S s..r.
prrform m1m1pu l 1l1r,n 111 yc,ur ,1pphr11lic,n,, For 11.indll's Buttonl.chck
t Window, I orn, Yo11 r, 111 do lhl, by uql11g llw MC.ll1<1bll•d F,11,e
1 nd~ub
111,111 I 1 'llll' 11, lu,wp h1,w yc,11 r,111 11,,, llw
2, Run tlw ,1pphc,1tion h prc~mg th,• F5 kev ,ind ch,:\,, the Cb..--!,,. me 11.1 ~ ~ Fomt
dirk tlw butl\>n, tlw t\,rm g,•ts diMbk,l •"- sh..>wn m the r~"lllt' ~,
~

AQ1onU::~tOltalllN...,_,__
l,-t, '"'" k,m1 l1-'" t\,,'h., ~"'th.:-ll.~,11• \\ '""' r..

Chan9mg th~ Ti
·t ",,,,,
t 11,,\
' h-t,
' ,~ f..
~\h.:
1%3
1H
----
~ f o n n ~ Styks
,~~

~
~
~
.....
~

"~~
~(d:\"""!DX'I' -\~

~ ...... ~et~.:rea,."e'1 \~m,iQl\"':'f-o...::t>~~ -~

~ =
C..-~?a
ED .,.,e.a ~.,.tlc£ N\)ft 5d the Tat a.:d ~~ • ~
~~l.:,a,.:;.~;;:,i.Fo::::tl:
..-.....si.~ -r~;~ ai'"'a.L:- a,:: ='' s~e- l.s s -_

--
~
= ~-,, :;,;; --.e
..-e -aa.·c :
=c~!"C:'·-s-:-. · <= = r - s - ~ ·-,s;::~'"5- e.,...
Ill=
-=rt ;;.....
- - ':_- =~--sr..:;f;::.-..r.:;: ~ =~
:i:c,.:c-ie:,,,.4~~--s m Sa. ;:;e itcmc:;.e1oi-ou::. ::.:rd.~.c:~amder
-Ul - ~e .:::rf'C't::::tl ,i::, ~:rFi.U'C!JD

a:ce~ - .e,;c~E~ID~ tn.?IJctFciot~ ~ ~ - ::- -;"-~ -:.


ram~

r - - - - - - - - - - -a~r.:.t:e:

figare4.11: Qaagilga"-"s a..-5111t


_a:.=
w:S!!!::: ~
::SU x i ::ie T a t ~ « . Fomal ID fora lkllds' m Fa:ufiu::i::dde ~ I D ~ . - ~
fnc::il=;tt:2 \~Form.

iJSJ a .~"'g and Hiding the Maximize Minimize and Close Buttons of
vr•rr I I
1 ...._,,,•,s Forms
~ :=n; ~ coce w1fh t h e ~ - Mmaizr batx:ns-. a;, .a:;a ~ b:::lclt ~the~
~ of the bI:1.. I.et, c::15111! a I indaw5 ~ ~ ~ 0 - R ~ ~ m lhe CD-
:
\'oa ca::. = - e these bmmns bl- 91!1!i11gllirbm sGldral!b. ~ ID 'F-H ~ ~ ~
~ a l L-.ec.oncer.B! form.as shmmm~U.2:

125
f ♦
Chapter4
nd
also set the initial position of w· w, ows Fonns In Visual Basic 2010
11 can a mdows Fonn bv
yortJll t,oad event: • writing the follow-mg code snippet in the
fo -·vate sub FormLLoad(Byval sender As s
prl ease. Load Y5tell.obJect, B}'Val e
'4e:furt?osition = FormstartPosition.centerPare.nt As Syste.-:i.E"venurgs) Hirnfles
End sub .
Ill preceding code sruppet, we have set the positi f the

LJ
:eat: multiform Windows applications in Visual Basic;~~- fonn as CenterParent Let's now learn how to

ating Multiform Windows Applications


ere511 se that you have designed your application with
~ 0 get data from the user, a summary form to displ:; ::~~ctory
form to welcome the user, a data entry
fo the Internet. You hav~ to n~w use or send the data of one fonn analysis results, and a logon form to connect
to entry form is reqwred m data analysis summary i to another, for mstance the data entEred in a
dataiications that contain multiple forms. I
onn. n such cases, you can create Windows Forms
Figure 4.12: Setting the ControlBox Property from the Properties Window apPunderstand multiform applications and how to comm
You can a1:° display o~ rude the ~~ ~d ~1aximize ?u~ons indepen~ently, by setting their values to True
or False usmg the MaximizeBox and lvtinimiz.eBox properties m the Properties window.
To lication called Multiform (also available in the
;l:tFonn. Perform the following steps:
CD-;::;:t 7=ge
·

an
them, let's create a new Windows
the Text property of Forml to
1. Add another form by selecting the Project➔ Add Windows Form option fr the Pr bar -
Specifying the Initial Position of Windows Forms shown in Figure 4.14: om o,ect menu , as
You can use a forms StartPosition property to specify its initial position on the screen. Assign the value for this
:~~ ~~m the StartPosition enumeration. The possible values for the position of Windows Forms are given
4
Table 4.5: Positions of Windows Forms
• ..... .J ,..,_.._
Value Description p .... .J ~
!:,t ... ....,..,...
':enterParen:c Centers the form ·within the bounds of its parent form

=
@ ---~ . _ ...,_
12: o.J Mia-
Cen te rSc reen Centers the form with the specified dimensions of the form using its Size property
~: c.-
WI'----

.
.,,._.-..qi .....
Manual Determines the starting position of the form using its Location and Size properties
WindowsDefaultBounds Positions the form at the default location of the Windows interface and has the bounds ..a
determined by Windows default :Dao
ti
h"rndowsDefault:Locauon Positions the form at the default location of the Windows interface and has lhe
dimensions specified in the form's Size property

Let's create a Windows Form application named InitialPosition (also available in the CD-ROM).

-
Figure 4.14: Selecting the AddWindows Fonn Option from Project Menu
You can set all these positions by using the Properties window of Forml, as shown in Figure 4.13:
The Add New Item dialog box appears, as shown in Figure 4.15:

ti s
,_...
OJ-y
,.t-
100"..
~ 000.0

::...--
'4"f,L40 "'

r-
k:a JOO.JOO

~=-:
"' ,,_
~-t:Z:m•
~~,._ I

Figure 4.13: Displaying the Properties of a Windows Form


Figure 4.15: Add New Item Dialog Box
126 127
Wlnctows Forms In Visual 84,sfc 2010

1I I I. lh '\,It\ I, lh II A n \\ lntn1. I, m

Figure 4.17 Olsplay!ng tho First Form


control is lr,111 f,•m•d lo f orm2 and th text of T
The In Figure I 18:
~•\J,uwn

Window, Form Add•d to the Projoct

Figure 4.18; Displaying the Multiform App cation


lid; t'H nl of tlw Bullon control of Fonn J • Let's now find out how to set up the startup form for the app'.:callOn.
t , nyv 1 As System. EventArgs) ·
Setting the Startup Form .
Well, the program is complete, and you have !>,Wed wntmg the best
ou greet the user is Form2, a~d when you actuall} test the program. \
~ou make the program start with Form2? To do so, perfonn the fo,uu"rlllt;><cl""
di r m th, pr l'dtng to1h•, fir t w1• ,111· n1•ating ,in object of Ponn2,
•• property tlMt w1· haVI' crl',ltl'd on Form2, with llw t1•xt l . Right-click the name of your project in the Solution Explorer a conll!.'d meru appe:in
t on r ,rm2 at runlmw At l,"t, w,• Ml' ijJ10wing l·orm2 by calling ils 2. Select Properties from the context menu, as shown in Figure -1.111,

yst Object, nyVal e M systc,m,CventArgs)

t uk the apphcallon
th r tBuxl pl d on I urml and tlwn click th1• r<ead
7
121
128
~
,
. ~
n,e Pf('Jc'<I !)('signer appear.- (Figure 4 ~0)
Sci.xi the Application tab in the lett_pan~. . .
--- .
find Lhe possible va lues to use for the Butt
WJndows Forms In Visual Basic 2010

- ~,...,..,--~ ...
· Selr-t Fcirnt: rn,m the drop-,fown hst ot the Startup form option on the nght, as shown in Figure _ :
4 20
you can B
St I E I
fable 4.6: Msg ox ye numeral ans
constant 2_alue
0
--
o'.:.:,.argument for the MsgBox in Table 4 6

Description
..

vbOKOnlY
- ~ hows ?~button only
~
~ylgnore
1
2
Shows OK and Cancel buttons
Shows Abort, Retry, and Ignore buttons
~ncel 3
Shows Yes, No, and Cancel buttons
~ 4
Shows Yes and No buttons
~eel 5
Shows Retry and Cancel buttons
~ 16
Shows Critical message
~ 32
Shows Warning query icon
~ion 48
Shows Warning message icon
~tion 64
Shows Information message icon
~uttonl 0
First button is default
~Button2 256
Second button is default
---;i;'oetaultButton3 512
Third button is default
~pplicationModal 0
Figure 4.20: Setting the Startup Form Application modal message box, which means the user must
respond to the message box before continuing work tn the
l\;(l\\ the program displa,·, the form you ha\'e selected first when the program runs. current application
--;bsystemModal 4096
Systen:' modal message box, which means all applications are
Displaying Messages unavailable until the user dismisses the message box
, ou ,an dtSpl lV me ,sages tor vour application in order to make the application simP-le and clear to understand. ~bMsgBoxSe tForeg round 65536 Specifies the message box window as the foreground window
Certnn me:;sage,, n<'ed to be con\'eyed by using messages boxes in order to display the proper messages on - vbMsgBoxRight 524288 Text will be right-aligned
ac1ton, to~• f"'rlormed Visual Basic 2010 pr<l\ides you with certain built-in functions and methods that help vbMsgBoxRtlReading 1048576 Specifies text should appear as right-to-left on RU systems such
1"0u 111 d1Spla11ng thr me,sages. as Hebrew and Arabic

Note that, this function returns a value from the MsgBoxResult enumeration. There are the possible
\ l'U can use the~ h.•,--ageBo, class built mto the .NET Framework to display messages and accept input from the MsgBoxResult values in tabular format as given in Table 4.7:
u...-er \\.-an> gomg to start with the MsgBo, function in this topic. The syntax for using Lhe MsgBox function:
Table 4.7: MsgBoxResult enumerations
Pub11c Function M.sgBox( B)Val Prompt As object, Optional syval Buttons As MsgBoxstyle =
MSg80.\St}le.0K0n1), Optional ByVal Title AS object = Nothing )As MsgBoxResult Member name - -••'-
'I;_. ~' LI

The a11,~ments I ou pas..sed to this function are as follows: OK The Ok is pressed


0 Fr pt - Rt~ to a ~1nng e,pre,,sion displayed as the message in the dialog box. The maximum length is Cancel The Cancel is pressed
about I :024 dwncters (dep,!ndtng on the width of the characters used). Abort The Abort is pressed
::l -Refers ti., th.- ,um ot value, 'pt'C1fying the number and type of buttons to display, the icon style Retry The Retry is pressed
lo u:,;c.• tlw 1dt•nttt\ of the dc>fault button, and the modality of the message box. If you omit Buttons, the
Ignore The Ignore is pressed
default 111lue 1s zeni \ ou can see the 1 able 4.6.
Yes The Yes is pressed
• -Ref.rs to tht• string t'\l'fl',-,ion di,plawd m tht> titlt? bar of the dialog box. Note that if you omit
l ill~ Lhl• appltc.,t10n n.imt> i- placl'<i in tht• title b.u. No The No is pressed

m
If you WBnt tho mossage box prompt to be moro than one line of text, you can force separate lines of text using a carriage re/um
Let's create a Windows application named MsgboxFunction (also available in the CD-ROM) to implement the
MsgBox function in your application. The application adds a Button and TextBox control and set the Text
r:::rocttlr (Cht(t3)) II hneloed charocter (Ch,rt0)), ore camege ,a/um/linefeed together (Chrf13) and Chrf10)) between each properly of Buttonl to MsgBox.
In the following example, we are adding OK and Cancel buttons to the message box, adding an info rm ation icon,
and making the message box modal (which means you have to dismiss it before doing anything el~). ln
addition, we check to see if the user dicked the OK button, in which case we display the message, You chcked
~K, in a text box control. You can use the code given in Listing 4.2 for the Click event handler of the Button] 10
0 display a message box using the MsgBox function:

131
133
Window , Forms In Vl111al Bn11c 20tO
M• ~i:· 11o,M1 1h1kl (,1ls<1 ,11,11 ., I,, In IW
u l\,lmcd i,, ,-(>mpll'I•• 1lw 1.1,k ~ ( Bullonl lo ( lid. M,· In ,1dd1l1on, add a nt'W W1rtdow- fo-rm
U,C folli>I\ ini; I,~ 11
- ,- F-o-rm2
-- an~d- add tw bu I
orrn , JnJ d,,,nf;<' th•• Bullnnl c,1pllon lo Chrk M.. « 111
110n
tlW ,aplion~, OK,<. ,inn•I, and f:nln Your I <'XI ,,.,.pccllvdy Add a I ex Ibent 111 in I rm2 nd
ntrol• 10th!' F, nn 1 1~11 11 Dialog Box. In f·1gurc 4.25, we h,we M'I lh1• l·ormHordmtyl properly of Forrn2 I• Fix D
41 iochc~, 1 ,•nl ol llullonl 1101110
cJ~ dialog box bortlt•r, Jnd ~c•I lh1• Con1rnJB11x prop<:rty to f al-.c.• 10 remove the corllrul box M ,r
1of Bu1tonl
ni!er As syst .Object, ByYal e As <;ystem. Eve

ox show( This Message Box Displayed Using


nt~rgs)

the
---
~;owlnTaskbar property of f•orm2 to f·al!-<!, a~ bhown 1n figure J 25

;";soxJcon, rnforma lion,


ss~ageBoxoPtions. oefaul toesktopon 1y))))
es)) Then . .,
· to NET 4 .O Progranmn ng

"-·
..,, lL-1 to 11111 the appULObon and cbck the Gick Me button. The output is shown in Figure 4.23.
fre&llitr~ - ;:.- ·

Figure 4.25: Creating a Dialog Box


Finally, set the DialogResult property of the OK button to OK, and set the same property of the Cancel button
to
Cancel. This property returns a value of the DialogResult enumeration when the clialog box is closed, so you can
Figure 4.23: Displayed Message Box Using the MessageBox.Sho w Method determine which button the user has clicked. The possible settings for the DialogResult propertv are shown
Ill
Click the 'i'5 button. the text Welcome to .NET 4.0 Programming set as a Labell caption, as shown in Table4.8:
Figurr414 Table 4.8: DialogResult Enumerations
Member Name Description
None Nothing is returned from the dialog box
OK Represents that the value returned by the dialog box LS OK
Cancel Represents that the value returned by the dialog~ is Can:el
Abort Represents that the value returned by the dialog box LS Abort
Retry Represents that the value returned by the dialog ~ is Retry
:gnore Represents that the value returned by the dialog box IS lgncre
Yes Represents that the value returned by the dialog box is Yi!>
No Represents that the value returned by the dialog box is No
Figure 4.24: Showing Text in Label1 Control
Let now discuss how lo create lhe dialog boxes.
Displaying and Reading Data from Dialog Boxes
Using Windows Forms to Create Dialog Boxes To display the dialog box when a user clicks the Oick Me button, create a new object 0£ the Form2. To display
Thr di.llog Im IS a form that enables "O to . I the dialog box, use the ShowDialog method, not the Show method, because ShowDialog returns a DialogResult
iO net'eS5ar)' that notlung can substituteulhe= ~:ct wilh ~e user and collect the value indicating the button the user has clicked. When the user clicks the OK button, the text from the text box
information. Dialog boxes are IS
lhev arr \ery basic In real appbcations eed uaJ Basic 2010 supports message boxes and input boxes, but displayed in the dialog box in the main form. The code for displaying the clialog box is shown in Listing -U:
nl Form allm, you to comert a form
ere.alt 1hr custom cli.atng bo>-eS
,n•;~u: 1
~o CTeJte custom dialog boxes. The FormBorderStyle property
og x using the Fixed Dialog enumeration. Let's now learn how to
Listiog 4.4: Demonstrating the Code for Displaying and Reading Data from Dialog Boxes
Private Sub Buttonl..Click C.,.1 . .ld.M•~m~-1""-aJMA)
Creating Dialog Box Handles Buttonl,c:11ck
Dim frm As Fonn2 ■ New
To create a di.Iii~ oo,. ,ou n If frm.showoialog () 1)1 i\
Dia!ogBox<:ontrol a I eed lo use the Windows form Th TextB0l(l, TIC
134 PP icauon (also available in the CD-ROM erefore, let's create a Windows application named End If
). Add a Button and a Textbox in Forml and set the End Sub

135
chapter4 _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ __
- - - - - - - - - - - - - - - - - - ~ W l ~ n d o w s Forms In Visuaf Basic 2010
no" knO" ho" displai daUI using a dialog box, the ne,t step 1s to accept or cancel the actions
10 ~ o n control, Button1, to l'orm1.
l ou
10 the requ
lJ'CDll'l"I of the apphu11Jon to Ix exccuttd.
use the Burton control as the OK and Cancel buttons m an application by using th .
accordio
g ! fy1odtfr the Text property of Forml to Owner Form, and button] lo Display Owned Form.
'"'- can f
proper!'
~ Button control For example if you \\,mt to use the Button control as OK be DialogRt~
, th B Ullon Ult
- Add another Windows Form, called Forrn2, to the WinOwnedform application.
D ogRr,UII propem a5 OK Sunilarh, 1f vou \\ant to use e utton control as Cancel b , set th 3 Add a Label control, labell, to Form2
l)i.llogRcsull propem as Cancel utton, ~l th~ ~- Modify the Text property of Form2 to Owned Form.
In the F nn2 funn of the [)ja]ogBox(ontrol applrcauon, \\e have set the D1alogResult property of B :· Add the following code snippet shown in Listing 4.5 in the Click event of Button J Control
::in2 OK and CmceJ. After setting the property, press the FS key to run the application. Th:tton1 an~ ~jsting 4.s: Demonstrating the ~ode for Click Event of Button1 Control
n F '!tir 4.26 --------

- ou tput IS prt~~~~e~ubsu~ut~~0t_7,~~kck(Byval se nd er As System.object , eyval e As Syste:n.Eve11tArgs)


•m ownedForml As Form2 = New Form2()
01
AddownedForm(0wnedForml)
Me· ownedForml.Labell.Text = "This is an owned form"
ownedForml. show()

7
End sub

...
_ Press the FS key to run the application. The output appears, as shown in figure .i.29·

nen ou k the Chck Me button m

"""'' m "" Enln Y=Tm""' i•"


Figure 4.26: Displaying the Forrn1
, a dialog box appears (Figure 4.27).

~d th, OK bul, ,s,ho~ in Figu« 4.27c

Figure 4.29: Output Form with a Button Control


When you click the Display_O~ned Form button, another form is displayed with a label containing the te,ct This
is a owned form, as shown m Figure 4.30,-:-----,--=-=.,..
.;o- ...

Figure 4.27: Displaying the Dialog Box


box d

-
ppeari; and your l\.-xt appears in the text box of Form1, as shown in Figure 4.28:

Figure 4.30: Displaying an owned Form

Creating Always-On-Top Windows Forms


Figure 4 28: Recovering Text from a Dialog Box You can make sure a form stays on top of all the other forms by setting its TopMO!>t property to True To crcatl'

.
ID,,,. bo,es II to tldd 11tway• B Can~/ button ao that 1f II usor opCJnS the dla/O(J bot by
u,nu,quence,
an always-on-top form, prrform the following slPps:
1. Crea te a Windows Forms application with the name AlwaysOnTopforiru; (which is also avJilabl~
CD- ROM). By default, the application contains a fonn, Forml
in
th
e

2. Add one more form, Form2, to the application 1


eating Owned Windows Forms 3. 51't the ropMost property of Forml to True and the TopMost propertv ofform2 False
10
° 2
f form tr ' 11, 1( .i u r m1r m11~ the owner form, till' ,,wnrd form is dl50 Add a Button control to Form1.Also &el the text property of the Button control Click Me tu Load Funn
dd uwnc-d form with th· AddOwni:df orm method, dnd rnnove 11 with tlw dnc.l 'f !.'XI property of the Forml to AlwaysOnTopForm.
,t od \', rr IL an apphra uon c.illcd WmOwncdf-orm (al'>() available in tlw CfJ ROM),
Add Llw following cool' 6nippet in the click event of the Button control
ned Wmduw Form ro do "'' perform the following bkps·
137
138
Figure 4.33 Dltpllyfng the FOffll w1Ct11utton Corttnll,
\\'hen I u r chcks th Ch k to 1-1 bu
Figul\'4 311

Figure 4.34: Dlaplaytng .... , . . . . . . . . . . _ , . . _ C....


\\'h,·n u"<'r chck, the 01d to Disp!Av butlllr\, it. bananl
r,gul'l'4 ~~
I ~ -

"allehoi controls such as buttons


orm rommon operation uch
controls mo\ e o.nd res1.ze ron

es and keep them hidden f


determine tf a control item
t to put the control items
ot npplv 111 a part1cul11.r FlglnYl: . . . . . . . . . . . . . --..a ..... c...
pla) and hide a control b Disabling and Enabling a-n,m
1llg t.-ps to hide or displ1
)au ,Ill\ USt' the Enabled pn,patJ ol . . .
~~~~~~~•,~~ ~m~ mR
u tilt' Pwpert1es window ol dw ___. • ea-• l"D• ◄uec
1 to Oick to Hide and of
Windows Forms In Visual Basic 2010

- ...
~ k s the En.iblc the control button, lhc disabled button is enabled, as shown in Figure 4.39.

Figure 4.39: Displaying an Enabled Control

cifying the Tab Order of Controls


Figure 4.36: Properties Window of the Button Contr~I
Sp~e usually use the mou~e to perform a_ctions such as selectmg, deselecting and scrolling. However, suppose
. . can write the code in the Code Editor window to enable o~ disable a control. Let's perfonn our mouse is not working and you still_ want to access the application. In that case, you try to access the
A11ernali1eh, ,ou bl d sable a control by writing the code in Code Editor: the
t..JI 0 mg steps to ena e or ' . . . Y Jication through your keyboard by usmg the Tab key. However, this is possible only if you have set the
'" '' r
Create· a l\.indow, Fonns app IC ation named DisableEnableControls
(also available
.
m the CD-ROM) . :~~ect tab order using the Properties window on the form. You can move from one control to another,
1 . hlighting the currently selected control, by using the Tab key from the keyboard ft is up to you to set the
F . and modifv, the Text property of buttonl to Disable the Control, and of button2
2 Add t1,o Buttons to orm1,
:~er in which the co_ntrols are ~vig~ted and even whether a control can be reached with the Tab key. To set the
to Enable the Control.
border of controls m your application, select a control whose tab order you want to set First of all, you need to
3. Modifr the Text property of forml to DisableEnableControl .
ta ake sure that the TabStop property of control is True. If the TabStop property is False then you cannot reach to
Add the following code snippet in the Click el'ents of buttonl _and button2. :ntrols using the Tab key. The Tablndex property of controls is used to set the control's position to access t~e
4
· Private sub ButtonLC_lick(ByVa7 sender As system.ObJect, syval e As System.EventArgs) controls by Tab button from the keyboard. The control you want to access first by Tab key, you need to set 1~
Handles suttonl. Cl 1 ck
Button 1. Enabled = False Tablndex property to O and next control to 1 and so on. When you run the application, the first control IS
highlighted; when you press the Tab key, the focus moves to the second control in the tab order and when yo_u
~;~v!~~sub euttonLcl; ck{ByVa l sender As system.object, syva l e As System. EventArgs) ress Tab again, the focus moves to the third control, and so on. To specify the tab order for the controls, lets
Handles eutton2. click ~eate a TabOrder (also available in the CD-ROM) application and then perform the folloY.'ing steps:
Buttonl.Enabled = True
E. d Sub 1. Set the Text property of Forml to TabOrder.
5_ Press the F5 key to execute the Di.sableEnableControls application. Figure 4.37 shows a form with two 2. Add the five buttons on the Form1 and set their Text property as Control1, Contro2. SQ on. as shown m
button controls: Figure 4.40:

Figure 4.37: Output Form with Two Button Controls


V.'hcn aser chcks the Disable the Control button, the button 1s disabled, as shown in the Figure 4.38:

Figure 4.40: Form with Five Button Controls


Figure 4.38: Displaying a Disabled Control
140
141
Windows Form• In Vlsual B • ~
autt 4 'T bln x
sutton T bind x
d ub
l•tlng 4 t, \\C hn,,• set thl' tnb orcl r for d1ft~rrn1 Button contro~ TIii!
In L ~ 2. "hu:h 01c,,n.c; when )OU prc-;s th<' Tab kl'Y the- fint t tabord f r the BullonS butt n c ntrol
1,n till' Cl•ntn•I,; bu lion control
14 "l('I hc-cnu'IC th~ Butta 1 m aft :-r CC'l.tll the pp t n t focu,
,on11"' 1 r, , 11 n nut IT\.lh llv focused wht.--n run the applic lion.
a• .11,,,,·11 in •1gur~
4
~
1:¢::.:.tfl :.
~:,-:.•

~--
~
lilr
r., ~

--.
~ ta
~L-w
~ F•
- -2
Figure 4.44: Displaying the Output of TabOrder Application
\'hen you press the Tab key first time the Controls gt!t fo :us, as shown m Figure 4 45
1
Figure 4 41: Properties Window for a Button Control
-e After -€ttJilg these tv. 0 propemes fm all the:;.e controls run the application.
h,..ht;..i......., ....__ The first B tt
•...,-""b'"'-....._ as ::,uu\ Tl m the Figure 4.42: u on control is

Figure 4.45: Changing the Focus of a Button Control

Specifying Access Character for Controls


Access characters are those characters that are underlined in menu names or control labcls Lets create an
application called AccessCharacters (also available in the CD-RO~I) in which we show how to specify access
figure 4.42: Displaying the Controls with the Tab Index Set

~ ~;~~:::p~.:+.fro;'::!f!) characters for the Button control. In this application, set the Forml caption to Access Charncter and place a

-
=d, thedother conhtrols ~e highlighted one by one in the order Button control on it, as shown in Figure 4.46:
r- ·~ 0
._r- -es wm ow, ass own rn the Figure 4.43:

,_
s--
•Al• ..... r -

~-
'P .........~

.i-
l!l <>-Uoo

,. __
u __....

You also th Figure 4.43: Changing the Focus of a Button Control


........
31 , ........
11,_
('_..__

Li .can set e tab order using the code, as shown in L1shng 4 6· 'II
o,,.-
o..~-

.1--
S)
sting 4.6: 11Ju5trabng the Cod f Settin . . 0-
P te Sub F e or g the Tab Order for Controls
o .-•
se.Loadorml__Load{ByVa
Buttonl Tabtndex •
sender As System.Object,
ByYal e As System. EventArgs) Handles
,--...
1
Button2. TabJndex " 4
Button3 Tablndex .. 5 Figure 4.46: Dl1pl1ylng the Form1 with • Button Control
143
Window,; Forms In Visual Basic 2010

~ uttc>nl. c;f ze • New Sizr.(100, 50)


suttonl.Loc.il ion New Point(O, OJ
d
t " .;ulJ . re; kt!y to run Lhl' .ipplica lion .ind click the Bu tton I button. The output is d1Splayed a5 follows
; rr•-'"" tlw17 , , Bullcin control Jnd Lhl' form ) as shown in Fi aurc 4 49:
(11·1thr•" ~" ~

~
:it,,; 'Is
, t.~.a..,~dur"""tl.T ~h)ffl.'1-AFi,'<~ .i_,,h,>\\11mf1gure-1.i-.
Figure 4.49: Di splaying th e Changed Size of a Fo rm and Button Control

. a control at Runtime _
Addtng 8dd 8 control in your application at runtime by using the Add method of the form's Controls collection.
You can application na med AddControl (also available in the CD-ROM) to learn how to add a control at
Let's crea; : r~:r:n the following steps to add a control at runtime:
run11111e.
Add a Button control, Button1, to Forrnl . . .
~: Set the Te~t property of Forrnl to Add Control and Buttonl to Click Me to Add a Control, as shown m
Figure 4.50.

Rsae 4-i- ';..Y"C wt=i a St."tt.:1n Control


.., ~ Cllfb\.l(l Fnm, with tht> ~ ch..uacter P of Print underlined
n::--,., ~ :\Jt-F ,~ cumbUl.ltlon from the keyboard. A message bo~

ql COGllllMmt1Stnp

Rgur. 4.43 :"Otlil S~if.g t.'le Access Characters for a Control u!1 "'"""''""
cm aesre acer,;~ c:b.tracters for ,-anety of commands. 'j! """"
ii!I

°""-
DaltTatPitka
!51 Dnd,,.,...,,

[II 0-.Upl)o<>
g
e -
:c2CT ro1: use the ~ method to move forms and controls and the Size and Location l!ll E""'-"I
~ to "" their d=,tlJD!-_ You can set the S'ixe property to a new Size object, and the Location property ~ r"
PQmt ob;t.,ct. The ~ u ; : n . -rou :-et m Size and Point objects are measured in pixels, as are all c--~~--~=~- -~--~
-~ m \ ,u,u &sic; roa create tbe,e obje...-ts by passing the values of the x and y dimensions to their
Figure 4.50: Displaying the Form with a Button Control
- - ~~ a;. >.l-iol\11 here· Size (x_dimefuion. y_dimension) and Point (x_location, y_location).
3. Add the following code snippet in the Click event of Butonl shown in Listing 4.8:
th.!! m the \ ,ua.( 5.1,,,c s:reen coordinate 5) stem, the upper left of the screen is the origin (0, 0).Positive x
lrlO'ei!....--e downwani, and ~iti, e y ,-a.lues increase to the right. Listing 4.8: Demonstrating the Code for Adding a Control at Runtime
Private sub suttonLClick(ByVal sender As systea.Object, ByVal e AS syste11.EventArgs)
..et s pertmm the loilo~ s ~ to learn how to mo\"e and resize the controls: 0 1
Crea~ a \foidows Fonn.,; application named MoveResizeControls (also available in the CD-ROM). oi:a~~w1;:x:~~ ;s
~~~~.!<ox • New TextBmCO
NeWTextBOX. Name ... "M)'-1:IXtlM!lt"
Add a Button control, Button}. to Form 1.
NeWTextaox.size "' New Size(150, 50)
Moo:£\ the Text property of Forml to Mo\"e and Resize Form. NeWTextBox.Location • New Point(50, ~0)
NeWTextaox.Text .. "Welcome to K•nt
4.. Add the lollowrng code snippet m the Click e\"ent of Butonl, as shown in Listing 4.7: cont ro1s . Add (NeWTextaox)
l.istmg V . IDustrating the Code for Mo,ing and Resizing Controls End Sub . . . e 51 ·
i;;te e~u~~1~a1~l c"k(ByVal sende· -s system.Object, Byval e As system.EventArgs) 4. Pr~ss the FS key to run and execute the application. The output 1s shown m Figur 4· ·
S1Ze = New Size(lOO , 100)
location = New Poi ot(0, O)

145
Windows Forms In Visual Basic 2010
~ a t e s the x-coor dinate
of a mouse click.
O 'I_ Indica tes they-c oordin ate
of a mou5e click.
O e Buttons proper ty holds one
of th ese members of the MouseBu t tons
'flt Left- Indic ates that the left mouse enu meration:
button Ls pressed
O r,1iddl e- Indica tes that the middle
mouse button is pressed
O None - Indica tes that no mouse
button is pressed
0
Right -Indic ates that the right mouse
Figure 4.51 : Output of the AddControl 0
button is pressed
application xautt on1- Indica tes that the first
the Click :\le to Add a Contro l button , 0
XButton is pressed
Gick a new text box ap pears in the form, )(BU t ton2 - Indica testha t
• ,. ..,.,_ . M1lil
as shown . F' the second XButton is pressed
0
m igure 1.52:
d/ing Keyboard Events
Han~ VIS~
. l Basic the follow ing events are available to
handle the keyboard events:
, .
Key Down -Occu rs when a key IS presse d down while the control has focus
l ~ .... ,,...c.... 0
KeyP ress -Occu rs when a key is presse
0 d while the control has focus
KeyUp -Occu rs when a key is release
0 d while the control has focus
For the Keyoown and Key~p events ..
, the e~ent handler receives an argum
data related to this event with these proper ent of type KeyEv entArg s, contau ung
ties:
Alt -Hold s a value indica ting wheth
0 er the ALT key is pressed
contr ol -Hold s a value indica ting
Figure 4.52: Form with a New Contro 0 whether the CTRL key is pressed
l Added Handl ed -Hold s or sets a value indica
Let's now discuss the mouse and keybo 0 ting whether the event is handled
ard events .
KeyCode -Hold s the keybo ard code
0 for a KeyDownor KeyUpeve nt
andling Common Events for Window KeyDa ta -Hold s the keybo ard data
As you know, Visual Basic
Forms and Controls 0
KeyV alue -Hold s the keybo ard value
for a KeyDownor KeyUp even t
2010 is an ~ent- ~ven langu a~. Clicki 0 for a KeyDownor KeyUp event
box are examp les of events . An event ng a button ~d enteri ng some text Modi fiers -Hold s the modifier flags . .
IS nothin g but an action that into a text 0 for a KeyDownor KeyUp event. This
which does 5'.'met hing as specif ied calls a functi on or may cause anothe indicates which modifier keys
in the code. You can contro l the flow r ev (Ctr!, Shift, and/ or Alt) are presse d.
There are mainly two types of events of an applic ation by handling ev;~'.
: Mouse events (event s genera ted shift -Hold sa value indicating wheth
and Keybo ard events (event s genera by supply ing the input through a mouse) 0 er the Shift key is p ressed
ted by supply ing the input throug h To handle the Ke yPres s events, .
the keybo ard). event handle rs take an argument of
type KeyP ressE ventA rgs, which
andling Mouse Events contains the following properties:
Handl ed -Gets or sets a value indicat
You can handl e mouse event s-such 0 ing whether the KeyPr ess event is
as mouse movem ents in forms and handled. If you set this value to
events for the Contro l class, which contro ls. There are the possible mouse True, Visual Basic will not handle this
is a base class for con trols and forms: key.
a KeyCha r -Hold s the charac ter corres
Q MouseDown - Occur s when the mouse ponding to the key pressed
pointe r is over the contro l and a mouse Let's learn how you can use these events
Q Mous e;:nte r-Occ urs when the mouse button is presse d in your progra m.
pointe r enters the contro l
□ Mous eHove r-Occ urs when the mouse
pointe r moves to and fro over the contro
Handling Keyboard and Mouse Events
□ Mous eLeav e-Occ urs when the mouse l 1. Create a Windo ws Forms application
named KeyboardMouseEvent (also availab
. .
pointe r leaves the contro l le ID the CD-ROM).
□ Mouse Move -Occu rs when the mouse 2. Add two Label, two TextBox, and oneBu
pointe r moves over the contro l tton controls to Forml .
□ Mouse Up-Oc curs when the mouse 3. Set the Text proper ty of Forml
pointe r is over the contro l and a mouse to Add Numb ers.

button is release d 4. Modify the proper ties of the added contra1s, as given
MouseWhee 1 - 0ccurs when the mouse
wheel moves , while the contro l has
· ID · Table 49..
The following proper ties of the Mouse focus
EventA rgs object are used to handle Table 4.9: Properties of Controls
the m ouse events :
□ Butto ns-Ind icates which mouse button Control
D Click s - Indicates the numbe
is presse d.
labell
- Enter First Numbe r
r of times the mouse button is presse Text
d and release d .
D Delta -Indic ates a calcula ted label2 Enter Second Numbe r
count of the numbe r of detent s the Text
rotation of the mouse wheel by one mouse wheel has rotated . A detent
notch. is !he
buttonl Text Add

46
147
Windows Forms in Visual Basic 2010

press 1 r,5 k~y to execute the KeyboJrdMoi,-,.f,vent application


~ tie
1,. ,er hovers the mouse ovl'r d rextBnxl , the background color of the Textlloc-<1 chango to red, as shown
Wf1cn ol u

-_
-
figure ,1.54·
1n • ,_, _..
.,..__
·-
.,,_ ..._._
,,,z -
m--

-
...+ .._
--
0 ·-
-

.. ~.,_,_
~W.. ' l . . \ ~ - ,
~ ~ I:.~"-

:, ,-,,.

Figure 4.54: Demonstrating the MouseEnterEvent


Next, when the mouse leaves the text box, the color change5 bl.i, I< o white. as shown m Figure 4 55
7. ......... ~~
Figure 4.53: Displaying the Form with Controls
5. Add the code gfren m Ll5ting -1.9 to the mouse and keyboard events of text boxes and button:
Listing 4.9: niustrating the Code for Handling Mouse and Keyboard Events
Private Sub TextBoxLMouseEnter(By\ial sender As System.Object, ByVal e As
systel!l. EventArgs) Handles TextBoxl.MouseEnter I
TextBoxl. Backcolor = color. Red I
Text:soxl.Forecolor = color.white
End sub
Private Sub TextBoxLMouseLeave(Byval sender As System.object, ByVal e As
system. EventArgs)
Textsoxl. Back col or = co 1or. whi t:e
Text:Boxl.Forecolor = color.Black
End Sub Figure 4.55: Demonstrating the MouseleaveEvenl . bers is
Private Sub TextBoxLKeyup(Byval sender As System.object, Byval e As Next, try to enter alphabets in the text boxes. A message box show with the message Enter onh mun
system. l\'l ndows. Forms. KeyE11ent:Args) Handles TextBoxl. Keyup
If (Notchar. IsNumber(chrw(e. KeyCode))) Then
MessageBox. show(" Enter only numbers")
displayed as shown in Figure 4.56:_ _ _ _ _ _ =......,._,,
wj/"'""1 C
Text:Boxl. Text = " "
End If
End sub
Private Sub Text:Box2JlouseEnter(ByVal sender As System.object, ByVal e As
syste111. EventArgs) Handles TextBox2 .MouseEnter
TextBox2.Backcolor = color.Red
TextBox2.Forecolor = color.white
End Sub
Private sub TextBox2JIOuseLeave(ByVal sender As System.object, ByVal e As
system. EventArgs) Handles TextBox2. MouseLeave
TextBox2.Backcolor = color.white
TextBox2.Forecolor = color.Black
End Sub
Pnvate sub TextBox2J(eyup(ByVal sender As System.object, ByVal e As
System.Windows. Forms. KeyEventArgs) Handles TextBox2. KeyUp
If (Notchar. IsNumber(Chrw(e. Keycode) )) Then
MessageBox.show("Enter only numbers")
TextBox2. Text = " "
End If Figure 4.56: Dl1pl1ylng • Mesuge Box b the total is displayed as a
d text boxes and clicks the Add utton.
Eo !~~vate sub ButtonLcl1ck(Byval sender As system.object, ByVal e As system.EventArgS) 8. When user enters two numbers in the
Handles Button 1. click message, as shown in Figure 4.57:
Msgsox('The total 1s " & crnt(TextBoxl.Text) + Cint(Texteox2.Text))
End Sub
149
Window, Form, In Vl,ual Basic 2010

ble .1o: Mouse Cursor Options


4
rs I
Description
constan.----
Specifies _the cursor for mouse whrel ope-rallon~ when the mou,e is moving and the
ranSW wmdo"" i5
scrolhng in south/we,t din.>chon, which means horimntal left or vertically downward direction

~ Specifil'S the cursor for mouw whf'('I ope-ralloM whm the mou,e i1 moving and the
scrolling horizontally to th,• left
window is

~
Specifies a four-headed CUJ"50r

~
Specifics a two-headed diagonal (north/ east and south/ west) cur.or

~
Specifie,. a two-headed ve?rtical (north/ south) cursor
Spt'Cifies a two-headed diagonal (northwest/southeast) cursor
SiZi!NWSE

~
Sp<.'Ci.fics a two-headed horizontal (west/east) cur,;or
rlgurt (.57: Dl1playlng the Total of Two Numbers
~
Spt.>cifies the up-arrow cursor usually used lo identify an insertion point

---
~
Specifies the cursor that appears when the mouse is over a vertical splitter bar
specifying the Mouse Cursor for Windows Forms and Controls Specifies the Wait cursor, usually of an hourglass shape
~r
h,u ,.i1i IN' 1lw (. ur,,1r pwp,•rt, 111 .. ,., tlw 11111u• 1• 1 ur ,or type wh1•n thr mouse moves
ovi·r I con trol. As
I.no" n \\ ui.!.111-s h1rm 1, nt,,, d1•rn ,•d I111111 tlw Control cla5s; therefore, cursor types are abo know about the various types of cursors that you can set for controls or forms, lets
applii•d fo Y00 create an
)ou can t,c.'I th,•<. urs,11 pwp,•rt) b\' sp,•, ll, In>; llw, ,,lu,•s giwn in I abk• 4 10; 10 N°W, you called Mouc,cCur~orControl (also available in the CD-ROM) to set the cursor types for the controls its
nn, apphcatllhon application. P~rform the following steps to complete this task:
,.. Table 4.10: Mouse Cursor Options ~m~
Set the Cursor property to one of the values of Table 4.10 using lhe Properties window, .
constant Descnptlon 1 as shown in
ArrSbrtin#: Figure -t.58·
.:;p,,11t,,, tlw "'ml1 1n,1ti,111 ol tlw Arrow cursor and llw Wail cursor
•OX
Ar,\l\\

-
R111ul Sv,lrm. Wlldon.FonasBulloa •
Cn~
Default ~!'('C1h,~ lh,· 01.'taull cul'Snr, usually ,,narrow cursor
Hand Spenl1<•s lh<' I l,uid cursor, usually ust>d when__1_,o_n_•r_in_g~ov_,_•r_a_W_c_b_hn_k_ _ _ _ AutoEllipw
_ _ _ _-.J Aut.SU. Fabe
H,•lp Sp,."1.-illl?~ thl' I telp cursor, ,1 rnmbinalion nl an arrow and a qu,•stion marl,;
AuloSa,Mode
BdColor O
0nnrOnly [•I
lbpht Specifies the cursor that appl.'ars when the mouse ib position,·d over a hori10ntnl ~phltt Coouol
r bM Bapooodlmlf0(no oo)
l&-am Specifies the I-beam cursor, which is ust>d to show wlwre tlw tl'xl cursor appears whrn BadipoaadlmlfTtlt
th, mc,u,.. 1 c....., - y,..
dic\..rd
No Speofies the cursor that indicates a p,1rlicular region lb m\'alid fnr till' cum·nl "I" r,1tion
NoMcwe2D Sp<>cihes the cursor for mouse wheel op,·rahons wlwn the mouse is not moving; h<llH'\l
r, 1h,• "'"d""
can be !>Crolled 111 either horizontal or wrtical direchon ,
Not-.\o,eHoriz Specifies the cursor for mouse wheel operations when th,• nu,u,e is not moving; how,·1
,·r, th,•" 111do11
can be scrolled ma hori10ntal dir,-ction
NoMo,1.'\'crt Sp<-cifics the cursor for mouse wheel operations when the mouS<' ,snot moving; ho1wwr,
_ _ _ _c_an_be_scro_l_led_in_a_,_wtical direc.;;.tio;...n;...._ _ _ _ _ _ _ _ _ _ llw II inJ,m
_ _ _ _ __ __,
l',rnEa$l Specifies the cursor for mouse wheel o~'t'rations when the mousl' is moving and
the window 1'
scrolling in horizontal right direction
l'anNI!. Spt>eifies the cursor for mouse wheel operations wh,,n the mou~e is moving and
the window "
scrolling in north/east direction, which means either horizontal right or vertically upward
dlJ\'ClIOn _
PanN,,rth Specifies the cursor for mouse whcel operations when the mouse is moving and ~ s-u

t:111~
the "~ndow IS
scrolling vertically ,nan upward direction
P,,nN\\ Specifk>s the rnrsor for mouse wh1>el operations when thl' mouse is moving and
the window ''
scrolling in norlh/w,·st din'Ction, which means hori,onlal left or vertically upward direction Figure 4.58: Proptrtlff Window for • Button Control
PanSf Specifies the cursor for mouse wheel operations when the mouse is moving and 2. Add Button, ListBox, and CheckBox controls to Forml.
the windo"· IS . . .
scrolling ,n south/ east direction, which means hori1ontal right or vertically downward
direction - 3. Set the Text property of Forml to MouseCursor, as shown in Figure 4.59.
r.anSouth Sp,>cifies the cursor for mouse whe<'I operations when the mouse is moving and
the window 15
.. scrolling vertically ,n a downward dim:hon
151
- - - - - - - - - - - - - - - - - - - -~Wl'!!_n~d~ow~s~Fo~rm~s!!_ln~~~l~su~a!!_IE_B~as~/c~20~1~0
,,----- r.-::-~- -,..-~-

u
-
,_..
o,., ........

,,,_
a<-
ll<-
,il"'""""'"'
--
.e 0...1'~

.__
lj!
SJ 0.-SS\<aitr\
Qo..nn-
1-.·-.
o ,-
;,, ,......
l"'! ~
Figure 4.61: Form with Changed Cursor Type for a Button Control
ill--...
~-... In case of the CheckBoxcontrol, the mouse pointer changes to the SizeNESW cursor type, as
shown in
......... Figure 4.62:
•}Mou..Cur,or ~

Figure 4.59: Displaying the Form with Controls


4. Add ~e following code snippet shown in Listing 4.10 in the Load event of Forml to set the cursor property
of, anous controls:
Listing _•UO: Hlustrating the Code for Setting the Mouse Cursor for a Form and Controls
Pr~~~~~ec;~~:ciorml._Load (ByVa l sender As System .object, ByVal e As system. EventArgs) Handles


Me.Cursor = cursors.Help
Buttonl.Cursor = cursors.sizeAll
CheckBoxl.curs or = cursors.sizeNESW
ListBoxl.curso r = cursors.AppSta rting
Endsub
cursor type Figure 4.62: Form with Changed Cursor Type for a Checkbox Control
In Listing 4.10, w_e set the cursor types for the Forml form and all the three controls. We set the Help
control in
for Form1 the SJZeAll cursor type for the Button control, the SizeNESW cursor type for the 01eckBox In case of the Listbox control, the mouse pointer changes to the AppStarting cursor type, as shown
and the AppStarting cursor type for the ListBo,-. control. Figure 4.63:
the mouse
5. Run the application b\ pressing the FS key from the keyboard. As a result, when you place
pointer on the form, the pointer appears as the Help pointer type, as shown in Figure 4.60:
• Mouseeursor lQ IS llllfllllll

Oloddlal1

~fl


OieckBaxl

Figure 4.63: Form with Changed Cursor Type for a Llstbox Control

Summary d h0 w to perform various actions on them, such as


chapter, you have learned about Windows Forms an . th tit! f Windows Form, setting the border
Figure 4.60: Form with Changed Cursor Type for Form1 In this
The
Similarly, the pointer type for the Button control changes to the SizeAll cursor type, as shown in Figure
4.61: adding controls, disabling and enabling Windows For_m, ch~~g e d ~:se buttons of a Windows Form.
of Windows Form, hiding and displaying the Maxmuze, M1IU11Uze an
153
r chap:a- ~""° de,cribe;: hm, ·
to a-eare mu b tomb an a \\ indows applicat10n.
messa;'.?e b(ne, and their creation ,
I n acid.itron,
. 1h c• chapter ~
_ the Ms~Bm:_ function and i\fes:agcBox.~how mcth~~ Jt als~ shows
dt.•c1ls
:llh
to create diaJo£ bcn-es Be:- de:5, \-OU e.:?.m about addmg controls to a Vvmdows Form and setting thcrr pr 0 1v
- 0 Pcrtj
FinalJ} the chap!er di._<;ruSse,: about handbng molL.<.e and keyboard cVC'nts. l'li.
ln the next chapta: learn about the\\ mdm\ s Forms controls, such as Button, I abcl, TextBox, and RrchTcxtBo
)(,

Quick Revise
QL \.\'hat a.re Static members?
Ans Static membezs are das, members, accessed direclly using the class name No object js needed for static
members.
Q2 Explain the l,\rmdows Form.
Ans A \\ indows form is a graphical user interface on which you display inf_ormation, either textual
graphical, to a user or use the input from the user in the form of text or images by using variety~;
controls.
Q3. Define the ActiveForm property of the Form class.
Ans. The ActiveForm property gets the currenlly active form of the application.
Q4. What is the difference between instance members and shared\static members?
Ans. The basic difference between a shared or static membP.r and an instance member is that to us
.h.
shared/static member, you do not need an object of that c1ass, b tit w1t mstance members, you needea
an
object\instance of class access the class members.
Q5. What is the use of Control Box property?
Ans. The ControIBox property is used to hide and show minimize, maximize, and dose buttons of Windows
form.
Q6. What is the function of IsMdiChild and IsMdiContainer properties of the Form class?
Ans. IsMd1Child property gets or sets a value that indicates if the form is an MDI child form whereas
lsMdiContainer property gets or sets a value that indicates if the form is a container for MDI child forms.
Q7. Which property indicates whether a window is normal, minimized, or maximized?
Ans. WindowState property.
QB. What i& the Access Character?
Ans. Access characters are those characters that are underlined in menu names or control labels.
Q9. Can you change the mouse cursor style for a particular !:Ontrol?
Ans Yes, you can change the cursor styk for a particular control by Cursor property of that particular controL
QJO. What is the function of TransparencyKey property of the Form class?
Ans.
The TransparencyKey property gets or :.et/; the color representing the transparent areas of the form.

You might also like