LẬP TRÌNH TRỰC QUAN - PHẦN II VISUAL BASIC - BÀI 19 potx

19 250 0
LẬP TRÌNH TRỰC QUAN - PHẦN II VISUAL BASIC - BÀI 19 potx

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Lập trình trực quan BÀI 19 DÙNG DIALOGS Dialogs (hội thoại) dùng để hiển thị tin tức nhận thơng tin từ chuột hay bàn phím từ người sử dụng tùy theo tình Chúng dùng để tập trung ý người sử dụng vào công việc chương trình nên hữu dụng chương trình Windows Có nhiều dạng Dialogs, thứ áp dụng cho hoàn cảnh riêng biệt Trong chương ta bàn qua loại Dialogs nghiên cứu cách ta dùng chúng: - Message Boxes - Input Boxes - Common Dialogs - Custom Dialogs 19.1 Message Boxes Message Boxes dùng để nhắc nhở người sử dụng chuyện gì, địi hỏi phản ứng từ người sử dụng Ví dụ ta chấm dứt chương trình MSWord mà chưa lưu trử hồ sơ MSWord nhắc ta lưu trử Dialog đây: 161 Lập trình trực quan Trong trường hợp người sử dụng click buttons Nếu click Yes xúc tiến việc lưu trử hồ sơ trước kết thúc chương trình MSWord Nếu click No MSWord lặng lẽ kết thúc Nếu click Cancel có nghĩa người sử dụng đổi ý việc chấm dứt chương trình trở lại tiếp tục dùng MSWord Ta dùng routine MsgBox để hiển thị Message Box coding hình đây: Parameter (thơng số) thứ MsgBox text message Close the program down?, parameter thứ nhì tập hợp icon (vbQuestion) số buttons (vbOKCancel) cách cộng hai constants: vbQuestion + vbOKCancel (hai buttons OK Cancel), parameter thứ ba title (tiêu đề) Dialog Trong ví dụ MSWord bên Constant icon buttons vbExclamation + vbYesNoCancel (ba buttons Yes, No Cancel) Ta chọn số loại buttons theo bảng đây: Constant Các buttons vbOKOnly OK vbOKCancel OK Cancel vbYesNo Yes No vbRetryCancel Retry Cancel vbYesNoCancel Yes No Cancel vbAbortRetryIgnore Abort Retry Ignore Constant icons ta dùng vbCritical, vbQuestion, vbExclamation vbInformation 162 Lập trình trực quan Khi Message Box mở ra, chương trình ngừng lại đợi người sử dụng phản ứng Ta nói Message Box hiển thị Modal Mode, dành ý tạm ngưng execution khác chương trình Sau người sử dụng click button, Message Box biến chương trình tiếp tục chạy từ dòng code dòng MsgBox Trong ví dụ ta dùng MsgBox Sub, ta dùng MsgBox Function để biết người sử dụng vừa click button Function MsgBox returns value (trả giá trị) mà ta thử để theo thi hành Ví 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 Các trị số Visual Basic intrinsic constants mà Function MsgBox returns là: Trị số Tên Const OK vbOK Cancel vbCancel Abort vbAbort Retry vbRetry Ignore vbIgnore Yes vbYes No vbNo Chúng ta hiển thị Text message Message Box thành nhiều dòng cách dùng Constant vbCrLf (CarriageReturn LineFeed) để đánh dấu chỗ ngắt khúc sau: MsgBox "This is the first line" & vbCrLf & " followed by the second line" 163 Lập trình trực quan Nếu thấy thường dùng MsgBox với icon buttons, có Text message khác nhau, viết Global Subroutine BAS module để dùng lại nhiều lần Ví dụ có Global Sub sau: Public Sub DisplayError(ByVal ErrMess As String ) MsgBox ErrMess, vbCritical + vbOKOnly, "Error" End Sub Mỗi lần muốn hiển thị Error message cần gọi Sub DisplayError với Text message mà không sợ dùng lầm lẫn icon Sau muốn đổi cách hiển thị Error message cần edit chỗ Nếu người sử dụng muốn lưu trữ tất errors xảy lúc runtime, cần thêm vài dòng code Sub Hiển thịError để viết Error message vào text file 19.2 Input Boxes Với Message Boxes, người sử dụng click lên button Đôi ta muốn người sử dụng đánh vào thêm kiện, trường hợp ta dùng Input Boxes Input Boxes giống giống Message Box, chuyên nhận input data từ người sử dụng khơng hiển thị icon Ví 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 Để ý parameters Function InputBox$ Parameter thứ Text message, parameter thứ hai Title Dialog, parameter thứ ba Default Input Value Đây value hiển thị sẵn Input Box xuất hiện, input user thường đánh vào người sử dụng cần click nút OK đủ Hai parameters cuối Optional (tùy chọn, có được, khơng có khơng sao) Nó X,Y coordinates Input Box đơn vị twips Hệ thống tọa độ lấy góc bên trái làm chuẩn với X=0, Y=0 164 Lập trình trực quan Input Box có hai dạng Functions: - InputBox$ - returns String đàng hoàng - InputBox - returns String nằm Variant variable Nếu click nút Cancel returned Value empty string, test empty string để nhận diện trường hợp Dưới ví dụ dùng 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 Mặc dầu Input Boxes dễ dùng, thực tế ta dùng lý sau đây: 165 Lập trình trực quan - Ta khơng thể làm lúc người sử dụng input data, phải đợi sau người sử dụng click OK bắt đầu xử lý input textstring Ngược lại ta dùng Textbox Form thơng thường, ta code Event handlers Events KeyPress hay Change để kiểm soát keystrokes người sử dụng - Input Boxes cho ta đánh vào text string Nhiều ta muốn người sử dụng đánh vào nhiều thứ nên cần phải có form riêng - Sau cùng, Input Boxes xem khơng đẹp mắt Chương trình dùng Input Boxes khơng chun nghiệp, ta cần phải dùng Custom Dialogs 19.3 Common Dialogs Chúng ta có để ý thấy chương trình Windows có dialogs để Open Save files ? Và tất chương trình có dialogs để chọn màu, font chữ hay để in ? Đó Dialogs thơng dụng thuộc Common Dialog Library MSWindows cho phép chương trình gọi Muốn dùng Dialogs VB6 ta phải reference Comdlg32.ocx IDE Menu command Project | Components chọn Apply Microsoft Common Dialog Control 6.0 Microsoft Common Dialog Control 6.0 cho ta sáu dạng Dialogs tùy theo gọi Method nào: 166 Lập trình trực quan Tên Method Open File ShowOpen Save File ShowSave Color ShowColor Font ShowFont Print ShowPrinter Help ShowHelp 19.4 Open Save File Dialogs Chúng ta mở Project với button tên CmdOpen Form1 đánh vào code sau 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 = ' 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" 167 Lập trình trực quan Exit Sub End If End Sub Hãy chạy chương trình click button Open, chương trình hiển thị error message đây: Lý ta quên bỏ Microsoft Common Dialog Control 6.0 vào Form1 Vậy doubleclick icon ToolBox Bây chạy chương trình lại click button Open để hiển thị Open Dialog Chúng ta chọn folder tùy ý cách di chuyển từ folder qua folder khác hay thay đổi disk drive Nếu click vào bên phải combobox File of type, dropdown thấy chọn hai loại Files liệt kê statement: 168 Lập trình trực quan Filter = "Executables (*.exe) | *.exe| Batch Files (*.bat)| *.bat" Sau chọn Filename có sẵn hay đánh tên vào File name textbox, click Open Sau đó, CommonDialog1.Filename chứa tên file chọn hay đánh vào Vì ta cho CancelError = True nên người sử dụng click Cancel chương trình generate Error số 32755 (cdlCancel) Ở ta bắt Error cách dùng On Error GoTo DialogError thử Err.Number= cdlCancel để hiển thị Error message đây: Save Dialog tương tự Open Dialog, ta dùng method ShowSave để hiển thị Trong ví dụ ta định nghĩa properties CommonDialog1 code Chúng ta dùng Properties Windows để định nghĩa chúng đây: 169 Lập trình trực quan Ngồi ra, dùng trang Properties CommonDialog1 để định nghĩa Properties lúc thiết kế cách right click Commondialog1 Form1 chọn Properties: Properties Pages Dialog hiển thị với Tab Open/Save As có sẵn lúc đầu, đánh tin tức sau: 170 Lập trình trực quan 19.5 Các loại Dialog có sẵn để dùng 19.5.1 Color Dialog Color Dialog cho người sử dụng cách chọn màu dễ dùng Ngồi màu có sẵn, người sử dụng tự tạo màu cho thêm vào bảng màu cung cấp, gọi Windows Palette cách click button Add to Custom Colors Chúng ta tạo màu cách click chỗ có màu theo ý bảng màu lớn hình vng nắm hình tam giác bên phải kéo lên, kéo xuống để thay đổi độ đậm màu hiển thị hộp vuông Color|Solid Khi vừa ý với màu hiển thị, click button Add to Custom Colors, màu cho thêm vào nhóm Custom Colors nằm phía dưới, bên trái 171 Lập trình trực quan Ta dùng method ShowColor để hiển thị Color Dialog Sau người sử dụng chọn màu rồi, ta trực tiếp assign cho property ForeColor hay BackColor control Trong ví dụ màu mà người sử dụng vừa chọn assigned cho background picturebox Picture1: Private Sub CmdSelectColor_Click() On Error GoTo NoColorChosen With CommonDialog1 CancelError = True ' Entire dialog box is hiển thịed, 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 172 Lập trình trực quan 19.5.2 Font Dialog Font Dialog cho ta chọn Font cho ảnh hay printer chọn màu để dùng cho chữ Font Ta dùng method ShowFont để hiển thị FontDialog Các chi tiết trình bày Font Dialog tùy thuộc vào trị số Flags sau: Constant Trị số Hiệu cdlCFScreenFonts Chỉ hiển thị Fonts printer hổ trợ cdlCFPrinterFonts Chỉ hiển thị Fonts ảnh, chưa tất printer hổ trợ cdlCFBoth Hiiển thị Fonts ảnh printer cdlCFScalableOnly &H20000 Chỉ hiển thị scalable Fonts TrueType fonts mà cài vào máy Nếu muốn cho người sử dụng tùy chọn để chọn màu thêm 256 vào trị số Flags 173 Lập trình trực quan Dưới code người sử dụng chọn Font màu 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ú ý: Nếu quên cho Flags số nói chương trình cho Error message sau: 19.5.3 Print Dialog Print Font cho ta giao diện giống Microsoft Office để chọn tùy chọn việc in Với Print Dialog ta chọn printer với đặc tính cách click button Properties hay button Preferences Ta định in từ trang đến 174 Lập trình trực quan trang document in copies Chỉ có điều phải lưu ý người sử dụng dùng Print Dialog để chọn Printer khác mà Print Dialog ta chọn Property PrinterDefault = True Printer trở thành Default Printer có hiệu lực vĩnh viễn Windows người sử dụng thay đổi lại Khác với Color Font Dialogs, Print Dialog khơng địi hỏi ta phải cho trị số Property Flags Ta cần dùng Method ShowPrinter để hiển thị Print Dialog Ba properties thường dùng sau người sử dụng chọn tùy chọn Print Dialog Copies, FromPage ToPage Để cho người sử dụng default values properties này, để sẵn trị số trước hiển thị Print Dialog Dưới code mẫu dùng print Dialog: Private Sub CmdSelectPrinter_Click() With CommonDialog1 FromPage = ToPage = Copies = ShowPrinter End With End Sub 175 Lập trình trực quan 19.5.4 Help Dialog Ta dùng method ShowHelp để hiển thị thơng tin giúp đỡ, nhớ phải cho CommonDialog trị số properties HelpFile HelpCommand Private Sub CmdHelp_Click() CommonDialog1.HelpFile = "YourProgram.hlp" CommonDialog1.HelpCommand = cdlHelpContents CommonDialog1.ShowHelp End Sub Để biết thêm chi tiết cách dùng ShowHelp, highlight chữ HelpContext source code VB6 ấn phím F1 chọn MsComDlg 19.6 Custom Dialogs Nhiều Message Box, Input Box hay dạng Common Dialogs không thích hợp cho hồn cảnh lập trình Trong trường hợp dùng Form bình thường để làm thành Dialog theo yêu cầu Nó cơng chút, thứ có màu sắc giống Forms khác chương trình, thứ hai ta muốn làm tùy ý Chỉ có bất lợi chương trình dùng nhiều tài nguyên cần thêm nhớ Sau ta thử triển khai Login Form tổng quát, dùng nhiều trường hợp Khi khởi động, chương trình hiển thị Login form yêu cầu người sử dụng đánh vào tên mật Sau đó, tên mật hợp lệ Form chương trình Cách ta thực cho chương trình khởi động với Sub Main BAS Module Sub Main gọi Sub GetUserInfo (cũng nằm Module) để hiển thị form frmLogin Modal mode để làm việc cách Message Box, Input Box hay Common Dialogs Khi form frmLogin dấu kín statement Me.Hide execution Sub GetUserInfo tiếp tục để chi tiết điền vào textboxes txtUserName txtPassword trả local variables strUserName strPassword Mã nguồn Sub Main Sub GetUserInfo liệt đây: Sub Main() Dim strUserName As String Dim strPassword As String ' Call local Sub getUserInfo to obtain UserName and Password 176 Lập trình trực quan 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 hiển thị đây: Sau user điền chi tiết click OK, tạm thời ta hiển thị thông điệp để xác nhận chi tiết 177 Lập trình trực quan Trong tương lai, viết thêm code để kiểm tra xem tên mật có hiệu lực khơng Có vài chi tiết form frmLogin để làm việc giống Common Dialog: Ta cho property BorderStyle frmLogin Fixed Dialog Ta cho Property PasswordChar textbox txtPassword "*" để người sử dụng điền mật khẩu, ta thấy dòng dấu hoa thị Ta cho Property StartupPosition form CenterScreen Property Default button cmdOK True để người sử dụng ấn phím Enter form coi tương đương với click button cmdOK Tương tự thế, Property Cancel button cmdCancel True để người sử dụng ấn phím Esc form coi tương đương với click button cmdCancel Tạm thời coding event click cmdOK cmdCancel đơn giản liệt kê đâ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 178 Lập trình trực quan 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 179 ... lấy góc bên trái làm chuẩn với X=0, Y=0 164 Lập trình trực quan Input Box có hai dạng Functions: - InputBox$ - returns String đàng hoàng - InputBox - returns String nằm Variant variable Nếu click... vbInformation 162 Lập trình trực quan Khi Message Box mở ra, chương trình ngừng lại đợi người sử dụng phản ứng Ta nói Message Box hiển thị Modal Mode, dành ý tạm ngưng execution khác chương trình Sau... Else MsgBox "Oh oh! - please type your age!", vbCritical + vbOKOnly, "Input Error" End If End Sub Mặc dầu Input Boxes dễ dùng, thực tế ta dùng lý sau đây: 165 Lập trình trực quan - Ta khơng thể làm

Ngày đăng: 24/07/2014, 16:21

Từ khóa liên quan

Tài liệu cùng người dùng

Tài liệu liên quan