Chapter 4 AP
Chapter 4 AP
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
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
•
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
~\\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 ,........
\\ 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
·--
,~-...
,,.,_,._
@-
El""-
,.~--
G-..a.
ii C.0.0..0,
---.....
,le-
..,
lil--
"-'--
~ o,ur-,._u,
'l o..c-
0 .,,_,.
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' -\~
~ =
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
r - - - - - - - - - - -a~r.:.t:e:
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
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
1I I I. lh '\,It\ I, lh II A n \\ lntn1. I, m
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
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
the
---
~;owlnTaskbar property of f•orm2 to f·al!-<!, a~ bhown 1n figure J 25
"-·
..,, lL-1 to 11111 the appULObon and cbck the Gick Me button. The output is shown in Figure 4.23.
fre&llitr~ - ;:.- ·
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 --------
7
End sub
...
_ Press the FS key to run the application. The output appears, as shown in figure .i.29·
-
ppeari; and your l\.-xt appears in the text box of Form1, as shown in Figure 4.28:
.
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
- ...
~ k s the En.iblc the control button, lhc disabled button is enabled, as shown in Figure 4.39.
~--
~
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
~ ~;~~:::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 __....
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
~
: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.
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
-_
-
figure ,1.54·
1n • ,_, _..
.,..__
·-
.,,_ ..._._
,,,z -
m--
-
...+ .._
--
0 ·-
-
.. ~.,_,_
~W.. ' l . . \ ~ - ,
~ ~ I:.~"-
:, ,-,,.
~ 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 ~
□
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
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.