You are on page 1of 15

Chng Mi Mt - Dng Dialogs

Dialogs (giao thoi) c dng hin th tin tc v nhn mouse hay keyboard input t users ty theo tnh hung. Chng c dng tp trung s ch ca users vo cng tc ng thi ca program nn rt hu dng trong cc chng trnh ca Windows. C nhiu dng Dialogs, mi th p dng cho mt hon cnh ring bit. Trong chng ny ta s bn qua 4 loi Dialogs chnh v nghin cu v khi no v cch no ta dng chng: 1. Message Boxes 2. Input Boxes 3. Common Dialogs 4. Custom Dialogs Message Boxes Message Boxes c dng nhc nh user mt chuyn g, v i hi mt phn ng no t user. Th d nh khi ta chm dt program MSWord m cha lu tr h s th MSWord s nhc ta lu tr n bng Dialog di y:

Trong trng hp ny user c th click mt trong 3 buttons. Nu click Yes th s xc tin vic lu tr h s trc khi kt thc program MSWord. Nu click No th MSWord s lng l kt thc. Nu click Cancel th c ngha user i vic chm dt program v tr li tip tc dng MSWord. Ta dng routine MsgBox hin th Message Box nh coding trong hnh di y:

Parameter (thng s) th nht ca MsgBox l text message Close the program down?, parameter th nh l tp hp ca icon (vbQuestion) v s buttons (vbOKCancel) bng cch cng hai constants: vbQuestion + vbOKCancel (hai buttons OK v Cancel), parameter th ba l title (tiu ) ca Dialog. Trong th d MSWord bn trn Constant ca icon v buttons l vbExclamation + vbYesNoCancel (ba buttons Yes, No v Cancel). Ta chn s v loi buttons theo bng di y:
Constant vbOKOnly vbOKCancel vbYesNo vbRetryCancel vbYesNoCancel vbAbortRetryIgnore Cc buttons OK OK Cancel Yes No Retry Cancel Yes No Cancel Abort Retry Ignore

Constant ca cc icons ta c th dng l vbCritical, vbQuestion, vbExclamation v vbInformation. Khi mt Message Box c m ra, c program ngng li v i user phn ng. Ta ni Message Box c hin th trong Modal Mode, n dnh mi s ch v tm ngng cc execution khc trong cng program. Sau khi user click mt button, Message Box s bin mt v program s tip tc chy t hng code ngay di hng MsgBox. Trong th d trn ta dng MsgBox nh mt Sub, nhng ta cng c th dng MsgBox nh mt Function bit user va mi click button no. Function MsgBox returns mt value (tr v mt gi tr) m ta c th th bit theo thi hnh. Th d nh: Private Sub CmdPrompt_Click() Dim ReturnValue As Integer ReturnValue = MsgBox("Close the program down", vbQuestion + vbOKCancel, "Exit Program") Select Case ReturnValue Case vbOK MsgBox "You clicked OK" Case vbCancel MsgBox "You clicked Cancel" End Select End Sub Cc tr s Visual Basic intrinsic constants m Function MsgBox returns l:
Tr s 1 Tn OK Const VbOK

2 3 4 5 6 7

Cancel Abort Retry Ignore Yes No

vbCancel vbAbort vbRetry vbIgnore vbYes VbNo

Bn c th hin th Text message trong Message Box thnh nhiu hng bng cch dng Constant vbCrLf (CarriageReturn v LineFeed) nh du nhng ch ngt khc nh sau: MsgBox "This is the first line" & vbCrLf & " followed by the second line" Nu bn thy mnh thng dng MsgBox vi cng mt icon v nhng buttons, nhng c Text message khc nhau, bn c th vit mt Global Subroutine trong .BAS module dng li nhiu ln. Th d bn c mt Global Sub nh sau: Public Sub DisplayError(ByVal ErrMess As String ) MsgBox ErrMess, vbCritical + vbOKOnly, "Error" End Sub Mi ln mun hin th mt Error message bn ch cn gi Sub DisplayError vi Text message m khng s dng lm ln icon. Sau ny mun i cch hin th Error message ch cn edit mt ch. Nu user mun bn lu tr tt c mi errors xy ra lc run-time, bn ch cn thm vi hng code trong Sub DisplayError vit Error message vo mt text file. Input Boxes Vi Message Boxes, user ch c th click ln mt button. i khi ta mun user nh vo thm mt t d kin, trong trng hp y ta c th dng Input Boxes. Input Boxes ging ging Message Box, nhng n chuyn nhn input data t user v khng hin th mt icon. Th d: Private Sub CmdGreeting_Click() Dim strReply As String strReply = InputBox$("Please enter your name", "What 's your name?", "John", 2000, 1000) MsgBox "Hi " & strReply & ", it 's great to meet you!", vbOKOnly, "Hello" End Sub cc parameters ca Function InputBox$. Parameter th nht l Text message, parameter th hai l Title ca Dialog, parameter th ba l Default Input Value. y l value c hin th sn trong Input Box khi n xut hin, nu l input user thng nh vo th user ch cn click nt OK l . Hai parameters cui cng l Optional (nhim , c cng c, khng c cng khng sao). N l X,Y coordinates ca Input Box trong n v twips. H thng ta ly gc trn bn tri lm chun vi X=0, Y=0.

Input Box c hai dng Functions:


InputBox$ - returns mt String ng hong InputBox - returns mt String nm trong Variant variable

Nu bn click nt Cancel th returned Value l empty string, bn c th test empty string nhn din trng hp ny. Di y l mt th d dng Function InputBox: Private Sub CmdFortuneTeller_Click() Dim varValue As Variant Dim intAge As Integer varValue = InputBox("Please enter your age", "How old are you?", "18") If IsNumeric(varValue) Then intAge = Val(varValue) If intAge < 20 Then MsgBox "You are a young and ambitious person", vbOKOnly, "Observation" Else MsgBox "You are a matured and wise person", vbOKOnly, "Observation" End If Else MsgBox "Oh oh! - please type your age!", vbCritical + vbOKOnly, "Input Error" End If End Sub Khi no nn dng Input Boxes Mc du Input Boxes rt d dng, trn thc t rt t khi ta dng n v nhng l do sau y: Ta khng th lm g c trong lc user input data, phi i sau khi user click OK th mi bt u x l input textstring. Ngc li nu ta dng mt Textbox trong mt Form thng thng, ta c th code trong cc Event handlers ca Events KeyPress hay Change kim sot cc keystrokes ca user. Input Boxes ch cho ta nh vo mt text string duy nht. Nhiu khi ta mun user nh vo nhiu th nn cn phi c mt form ring. Sau cng, Input Boxes xem khng p mt. Program dng Input Boxes c v nh khng chuyn nghip, do ta cn phi dng Custom Dialogs.

Common Dialogs Bn c thy hu nh mi programs trong Windows u c cng nhng dialogs Open v Save files ? V hu nh tt c programs u c cng dialogs chn mu, font ch hay in ? l v cc Dialogs thng dng y thuc v Common Dialog Library ca MSWindows v cho php cc program gi.

Mun dng cc Dialogs y trong VB6 ta phi reference Comdlg32.ocx bng IDE Menu command Project | Components... ri chn v Apply Microsoft Common Dialog Control 6.0.

Microsoft Common Dialog Control 6.0 cho ta su dng Dialogs ty theo gi Method no:
Tn Open File Save File Color Font Print Help Method ShowOpen ShowSave ShowColor ShowFont ShowPrinter ShowHelp

Open v Save File Dialogs Bn hy m mt Project mi vi mt button tn CmdOpen trong Form1 v nh vo code sau y cho Sub CmdOpen_Click: Private Sub CmdOpen_Click() On Error GoTo DialogError With CommonDialog1 .CancelError = True ' Generate Error number cdlCancel if user click Cancel .InitDir = "E:\VB6" ' Initial (i.e. default ) Folder

.Filter = "Executables (*.exe) | *.exe| Batch Files (*.bat)| *.bat" .FilterIndex = 1 ' Select ""Executables (*.exe) | *.exe" as default .DialogTitle = "Select a program to run" .ShowOpen ' Lauch the Open Dialog MsgBox "You selected " & .FileName, vbOKOnly + vbInformation, "Open Dialog" End With Exit Sub DialogError: If Err.Number = cdlCancel Then MsgBox "You clicked Cancel!", vbOKOnly + vbInformation, "Open Dialog" Exit Sub Else MsgBox "Error in Dialog's use: " & Err.Description, vbOKOnly + vbCritical, "Error" Exit Sub End If End Sub Hy chy program y v click button Open, program s hin th error message di y:

l v ta qun b mt Microsoft Common Dialog Control 6.0 vo Form1. Vy bn hy doubleclick icon ca n trong ToolBox. By gi hy chy program li v click button Open hin th Open Dialog.

Bn c th chn folder no ty bng cch di chuyn t folder ny qua folder khc hay thay i disk drive. Nu bn click vo bn phi ca combobox File of type, n s dropdown cho thy bn c th chn mt trong hai loi Files nh lit k trong statement: .Filter = "Executables (*.exe) | *.exe| Batch Files (*.bat)| *.bat" Sau khi chn mt Filename c sn hay nh mt tn vo File name textbox, bn click Open. Sau , CommonDialog1.Filename s cha tn file bn chn hay nh vo.

V ta cho .CancelError = True nn nu user click Cancel program s generate mt Error s 32755 (cdlCancel). y ta bt Error y bng cch dng On Error GoTo DialogError v th Err.Number= cdlCancel hin th Error message di y:

Save Dialog cng tng t nh Open Dialog, ta dng method ShowSave hin th n.

Trong th d trn ta nh ngha cc properties ca CommonDialog1 bng code. Bn cng c th dng Properties Windows nh ngha chng nh di y:

Ngoi ra, bn cng c th dng cc trang Properties ca CommonDialog1 nh ngha Properties lc thit k bng cch right click Commondialog1 trn Form1 ri chn Properties:

Properties Pages Dialog s hin th vi Tab Open/Save As c sn lc u, bn c th nh cc tin tc nh sau:

Color Dialog Color Dialog cho user mt cch chn mu rt d dng. Ngoi nhng mu c sn, user c th t to ra mt mu ri cho n thm vo trong bng mu c cung cp, gi l Windows Palette bng cch click button Add to Custom Colors.

Bn to ra mt mu bng cch click ch c mu theo trong bng mu ln hnh vung ri nm hnh tam gic bn phi ko ln, ko xung thay i m ca mu nh hin th trong hp vung Color| Solid. Khi va vi mu hin th, bn click button Add to Custom Colors, mu y s c cho thm vo nhm Custom Colors nm pha di, bn tri.

Ta dng method ShowColor hin th Color Dialog. Sau khi user chn mt mu ri, ta c th trc tip assign n cho property ForeColor hay BackColor ca mt control. Trong th d di y ci mu m user va chn c assigned cho background ca picturebox Picture1: Private Sub CmdSelectColor_Click() On Error GoTo NoColorChosen With CommonDialog1 .CancelError = True ' Entire dialog box is displayed, including the Define Custom Colors section .Flags = cdlCCFullOpen .ShowColor ' Launch the Color Dialog Picture1.BackColor = .Color ' Assign selected color to background of Picture1 Exit Sub End With NoColorChosen: ' Get here if user clicks the Cancel button MsgBox "You did not select a color!", vbInformation, "Cancelled" Exit Sub End Sub Font Dialog Font Dialog cho ta chn Font cho mn nh hay printer v chn mu dng cho ch ca Font. Ta dng method ShowFont hin th FontDialog. Cc chi tit trnh by trong Font Dialog ty thuc vo tr s ca Flags nh sau:
Constant cdlCFScreenFonts cdlCFPrinterFonts cdlCFBoth Tr s 1 2 3 Hiu qu Ch hin th cc Fonts printer h tr Ch hin th cc Fonts ca mn nh, cha chc tt c u c printer h tr Hiin th cc Fonts mn nh v printer

cdlCFScalableOnly

&H20000

Ch hin th cc scalable Fonts nh TrueType fonts m bn ci vo my

Nu bn mun cho user nhim chn mu th thm 256 vo tr s ca Flags.

Di y l code cho user chn Font v mu ca Label1. Private Sub CmdSelectFont_Click() On Error GoTo NoFontChosen CommonDialog1.CancelError = True ' Causes the dialog box to list only the screen fonts supported by the system. CommonDialog1.Flags = cdlCFScreenFonts + 256 ' Add 256 to include Color option CommonDialog1.ShowFont ' Launch the Font Dialog With Label1.Font .Bold = CommonDialog1.FontBold .Italic = CommonDialog1.FontItalic .Name = CommonDialog1.FontName .Size = CommonDialog1.FontSize .Strikethrough = CommonDialog1.FontStrikethru .Underline = CommonDialog1.FontUnderline End With Label1.ForeColor = CommonDialog1.Color Label1.Caption = "Hello world!!!, this is a Font Dialog Demo" Exit Sub NoFontChosen: MsgBox "No font was chosen!", vbInformation, "Cancelled" Exit Sub End Sub

Ch : Nu bn qun cho Flags mt trong nhng hng s ni trn program s cho mt Error message nh sau:

Print Dialog Print Font cho ta mt giao din cng ging nh trong Microsoft Office chn nhng nhim v vic in. Vi Print Dialog ta c th chn printer no vi nhng c tnh no bng cch click button Properties hay button Preferences. Ta cng c th quyt nh in t trang no n trang no ca document v in bao nhiu copies. Ch c iu phi lu l nu user dng Print Dialog chn mt Printer khc m trong Print Dialog ta chn Property PrinterDefault = True th Printer y s tr thnh Default Printer v n cng s c hiu lc vnh vin trong c Windows cho n khi user thay i li. Khc vi Color v Font Dialogs, Print Dialog khng i hi ta phi cho mt tr s ca Property Flags. Ta ch cn dng Method ShowPrinter hin th Print Dialog. Ba properties thng c dng nht sau khi user chn cc nhim ca Print Dialog l Copies, FromPage v ToPage. cho user cc default values ca nhng properties ny, bn c th sn cc tr s trc khi hin th Print Dialog.

Di y l code mu dng print Dialog: Private Sub CmdSelectPrinter_Click() With CommonDialog1

.FromPage = 1 .ToPage = 1 .Copies = 1 .ShowPrinter End With End Sub Help Dialog Ta dng method ShowHelp hin th cc thng tin gip , nhng nh phi cho CommonDialog t nht tr s ca cc properties HelpFile v HelpCommand. Private Sub CmdHelp_Click() CommonDialog1.HelpFile = "YourProgram.hlp" CommonDialog1.HelpCommand = cdlHelpContents CommonDialog1.ShowHelp End Sub bit thm chi tit v cch dng ShowHelp, highlight ch HelpContext trong source code VB6 ri n phm F1 v chn MsComDlg. Custom Dialogs Nhiu khi Message Box, Input Box hay cc dng Common Dialogs vn khng thch hp cho hon cnh lp trnh. Trong trng hp y bn c th dng mt Form bnh thng lm thnh mt Dialog cy nh, l vn. N hi mt cng hn mt cht, nhng th nht n c nhng mu sc ging nh cc Forms khc trong chng trnh, v th hai ta mun lm g ty . Ch c ci bt li l chng trnh s dng nhiu ti nguyn hn, ni thng ra l cn thm mt t memory. Sau y ta th trin khai mt Login Form tng qut, c th dng trong nhiu trng hp. Khi khi ng, program ny s hin th mt Login form yu cu user nh vo tn v mt khu. Sau , nu tn v mt khu hp l th ci Form chnh ca program mi hin ra. Cch ta thc hin l cho program khi ng vi mt Sub Main trong .BAS Module. Sub Main s gi Sub GetUserInfo (cng nm trong cng Module) hin th form frmLogin trong Modal mode n lm vic cng mt cch nh Message Box, Input Box hay Common Dialogs. Khi form frmLogin c du kn bng statement Me.Hide th execution trong Sub GetUserInfo s tip tc chi tit in vo cc textboxes txtUserName v txtPassword c tr v local variables strUserName v strPassword. M ngun ca Sub Main v Sub GetUserInfo c lit ra di y: Sub Main() Dim strUserName As String Dim strPassword As String ' Call local Sub getUserInfo to obtain UserName and Password GetUserInfo strUserName, strPassword If strUserName = "" Then MsgBox "Login failed or aborted", vbInformation, "login Aborted" Else MsgBox "User " & strUserName & " logged in with password " & strPassword, vbInformation, "Login accepted" ' Check UserName and Password here ' If valid password then show the Main form of the program which is implemented separately... ' frmMain.Show

End If End Sub Private Sub GetUserInfo(ByRef sUserName As String, ByRef sPassword As String) ' Invoke frmLogin form in Modal mode frmLogin.Show vbModal ' As soon as frmLogin is hidden, the execution gets here sUserName = frmLogin.txtUserName ' assign the form's txtUserName to sUserName sPassword = frmLogin.txtPassword ' assign the form's txtPassword to sPassword Unload frmLogin ' Unload form frmLogin End Sub Login form c hin th nh di y:

Sau khi user in chi tit v click OK, tm thi ta ch hin th mt thng ip xc nhn cc chi tit y.

Trong tng lai, bn c th vit thm code kim tra xem tn v mt khu c hiu lc khng. C mt vi chi tit v form frmLogin n lm vic ging ging mt Common Dialog: Ta cho property BorderStyle ca frmLogin l Fixed Dialog. Ta cho Property PasswordChar ca textbox txtPassword bng "*" khi user in mt khu, ta ch thy mt hng du hoa th. Ta cho Property StartupPosition ca form l CenterScreen. Property Default ca button cmdOK l True khi user n phm Enter trong form l coi nh tng ng vi click button cmdOK. Tng t nh th, Property Cancel ca button cmdCancel l True khi user n phm Esc trong form l coi nh tng ng vi click button cmdCancel.

Tm thi coding ca event click ca cmdOK v cmdCancel ch n gin nh lit k di y: Private Sub CmdCancel_Click() ' Clear txtUserName and txtPassword txtUserName = "" txtPassword = "" ' Hide the Form to get out of Modal mode

Me.Hide End Sub Private Sub CmdOK_Click() ' Hide the Form to get out of Modal mode Me.Hide End Sub

You might also like