Programming language Visual Basic 6 (Chapter 11 - Using the Dialogs dialog)



  1. Message Boxes
  2. Input Boxes
  3. Common Dialogs
  4. Custom Dialogs

Message Boxes

Message Boxes  are used to remind what a user, and requires a certain response from the user. For example when we terminate MSWord program without filing the MSWord will prompt you store it with the following Dialog:

This image has been resized in order to avoid breaking the interface. Click here to view photo in full size (586x347)

In this case the user can click one of three buttons. If you click  Yes  , it will expedite the filing before the end of MSWord program. If you click  No  , the MSWord will quietly end. If you click  Cancel  , the change means that an end user program and return to continue using MSWord.

Routine we use  MsgBox  to display the Message Box like coding in the image below:

This image has been resized in order to avoid breaking the interface. Click here to view photo in full size (685x224)
Parameter (parameter) is the first text message MsgBox Close the program down?,second parameter is a set of icons (vbQuestion) and some buttons (vbOKCancel) by adding the two constants: vbQuestion + vbOKCancel (two buttons OK and Cancel ), the third parameter title (title) of the Dialog.

In the example above Constant MSWord icon and the buttons are vbExclamation +vbYesNoCancel (three buttons Yes, No and Cancel).

We choose the number and types of buttons in the table below:
ConstantCác buttons
vbOKCancelOK   Cancel
vbYesNoYes   No
vbRetryCancelRetry   Cancel
vbYesNoCancelYes   No   Cancel
vbAbortRetryIgnoreAbort   Retry   Ignore
Constant của các icons ta có thể dùng là vbCritical, vbQuestion, vbExclamation và vbInformation.

When a Message Box is opened, the program stop and wait for user response. We say Message Box is displayed in  Modal Mode , it is for all the attention and suspend the execution of the same program. After the user click a button, the Message Box will disappear and the program will continue running from just below the row of code MsgBox.

In the above example we use MsgBox as a sub, but we can also use the MsgBox function as a user to know just click any button. MsgBox function returns a value (return value) which we can then know which to implement. For example:

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 
The intrinsic value of constants that Visual Basic MsgBox function returns are:
You can display text messages in the Message Box in many rows using Constant  vbCrLf (CarriageReturn and LineFeed) to mark the track breaks as follows:

MsgBox "This is the first line" & vbCrLf & " followed by the second line" 
If you find yourself using the same MsgBox icons and buttons, but have different text message, you can write in a Global Subroutine. BAS module to be used again and again. For example you have a Global Sub as follows:

Public Sub DisplayError(ByVal ErrMess As String ) 
   MsgBox ErrMess, vbCritical + vbOKOnly, "Error" 
End Sub 
Every time you want to display an error message you just call the Sub DisplayError Text message without fear of mistakenly using icons. Later want to change the error message displayed just edit in one place. If the user wants you to store all the errors occur at run-time, you just add some code found in the Sub DisplayError to write error messages into a text file.

Input Boxes

Message Boxes with, the user can click on a button. Sometimes we want to hit a little more user data, in the event that we can use the  Input Boxes .

Input Message Box Boxes seed varieties, but it specializes in getting data from user input and display an icon. For example:

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 
Notice the parameters of the InputBox $ function. The first parameter is the textmessage, the second parameter of the Dialog Title, Tuesday is the Default Inputparameter Value. This is the value displayed in the Input Box available when it appears,if the user input that is often imposed on the user can just click the OK button is enough.Two last parameters are Optional (elective, may well be, not okay.) It is the X, Ycoordinates in units of twips Input Box. Coordinate system taking the upper left corneras a standard with X = 0, Y = 0.

Input Box có hai dạng Functions:
  • InputBox$ - returns một String đàng hoàng
  • InputBox  - returns a String in the Variant variable
If you click the Cancel button trả Value is empty string, you can test the empty string to identify this case.

Here is an example using InputBox Function:

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" 
         MsgBox "You are a matured and wise person", vbOKOnly, "Observation" 
      End If 
      MsgBox "Oh oh! - please type your age!", vbCritical + vbOKOnly, "Input Error" 
   End If 
End Sub 

When to use Input Boxes

Although easy to use Input Boxes, in fact we rarely use it because of the following reasons:
  • You can not do anything while the user input data, must wait after the user clicks OK, then start handling input textstring. Conversely, if we use a regular textbox in a form, you can code in the handlers of Events Event  KeyPress  or  Change  to control the user's keystrokes.
  • Input Boxes for only one type into a single text string. Sometimes we want user reviews on many things, so should have a separate form.
  • Finally, Input Boxes unsightly view. Program seems to use Input Boxes are not professional, so we need to use  Custom Dialogs .

Common Dialogs

You have noticed that almost all have the same programs in Windows to the Open and Save Dialogs files?And almost all programs have the same Dialogs to select the color, font, or to print? This is because the common belong Dialogs Common Dialog Library of MSWindows and the program calls for.

Dialogs want to use it in VB6 we must reference  Comdlg32.ocx  by IDE menu command  Project | Components ...  and then click Apply  Microsoft Common Dialog Control 6.0 .

Microsoft Common Dialog Control 6.0 Dialogs for our six types depending on what method to call:

Open FileShowOpen
Save FileShowSave

Open và Save File Dialogs

Open a new Project with a button named Form1 and type CmdOpen in the following code to 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 
   If Err.Number = cdlCancel Then 
      MsgBox "You clicked Cancel!", vbOKOnly + vbInformation, "Open Dialog" 
      Exit Sub 
      MsgBox "Error in Dialog's use: " & Err.Description, vbOKOnly + vbCritical, "Error"
      Exit Sub 
   End If 
End Sub 

Let him run the program and click the Open button, program will display the errormessage below:

That's because we forgot to put a Microsoft Common Dialog Control 6.0 on Form1. So be it DoubleClick's icon in the Toolbox. Now run the program again and click the Open button to display the  Open Dialog .
This image has been resized in order to avoid breaking the interface. Click here to view photo in full size (563x416)

You can choose any folder you like, by moving from this folder to another folder or disk drive change. If you click on the combobox to the right of  the File of type , it will dropdown to show that you can choose one of two categories as listed in the Files statement:

.Filter = "Executables (*.exe) | *.exe| Batch Files (*.bat)| *.bat" 

After choosing a filename is available, or type a name into the  File name  text box, click  Open . Then, CommonDialog1.Filename will contain the file name you have selected or entered.

Because for us. CancelError = True if the user should click Cancel the program willgenerate an Error 32 755 (cdlCancel). Here we catch that error by using the On ErrorGoTo Err.Number = cdlCancel DialogError and try to show the error message below:

Save Dialog is similar to the Open Dialog, ShowSave method we use to display it.
This image has been resized in order to avoid breaking the interface. Click here to view photo in full size (563x416)

In the above example we define the properties of CommonDialog1 by code. You can also use the Properties Windows to define them as follows:

Also, you can also use the Properties page of the Properties as defined CommonDialog1 to design by right click on Form1 and select Commondialog1  Properties :

Pages Dialog Properties tab displays the  Open / Save As  is available at the beginning, you can type the following information:

Color Dialog

Color Dialog  to the user selecting a color easy to use. Besides the color is available, users can create and then give it a color palette to be added to the offer, called the  Windows palette  by clicking the button Add to Custom Colors .
This image has been resized in order to avoid breaking the interface. Click here to view photo in full size (771x358)

You create a color by clicking where it has the color palette in the big square and then hold triangle to the right to pull up, pull down to change the color saturation of the square box shown in  the Color | Solid .When satisfied with the color display, click the button  Add to Custom Colors , color would be added to the group Custom Colors  located below, left.

We use the method  ShowColor  to display the Color Dialog. After the user has selected a color, then we can assign it directly to the ForeColor or BackColor property of a control. In the example below which the user has selected a color for the background of the picturebox is gán 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 
   ' Get here if user clicks the Cancel button
   MsgBox "You did not select a color!", vbInformation, "Cancelled" 
   Exit Sub 
End Sub 
You can download the source code of this program FontDialog.

Font Dialog

Font Dialog  was chosen for the screen or printer fonts and colors to choose the font used for text. We use the method  ShowFont  FontDialog to display. The information presented in the Font Dialog depending on the value Flags are as follows:

cdlCFScreenFonts1Show only the printer fonts support
cdlCFPrinterFonts2Fonts only display of the screen, not necessarily all printer support
cdlCFBoth3Hiien marketing the screen and printer fonts
cdlCFScalableOnly&H20000Scalable display only TrueType fonts as fonts that you have installed on your computer
If you want the user to select arbitrary color, then add 256 to the value of the Flags.

Here is the code for the user to select the font and color of 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 
   MsgBox "No font was chosen!", vbInformation, "Cancelled" 
   Exit Sub 
End Sub 
Note: If you forget one of the constants for the Flags of the said program will give an error message as follows:

You can download the source code of this program FontDialog.

Print Dialog

Print Font  gives us an interface similar to Microsoft Office in order to choose the elective on printing. With the Print Dialog you can select any printer with features that by clicking the button  Properties  button or Preferences . We can also decide to print from page to page of document and print as many copies. Only thing to note is that if users use the Print Dialog to select a different printer in Print Dialog which I have chosen Property  PrinterDefault = True  then it will become a Default Printer Printer and it will be permanently in effect until both Windows when the user changes again.

Unlike Color and Font Dialogs, Print Dialog does not require us to give a Flags value of the Property. I just use Method  ShowPrinter  to display the Print Dialog. The three most commonly used properties after the user select the Print Dialog is arbitrary  Copies, FromPage  and  ToPage . To give users the default values of these properties, you can leave the available values before displaying the Print Dialog.

Below is a sample code using print dialog:

Private Sub CmdSelectPrinter_Click() 
   With CommonDialog1 
      .FromPage = 1 
      .ToPage = 1 
      .Copies = 1 
   End With 
End Sub 

Help Dialog

We use the method  ShowHelp  to display help information, but remember to give at least CommonDialog value of the properties  HelpFile  and  HelpCommand .

Private Sub CmdHelp_Click() 
   CommonDialog1.HelpFile = "YourProgram.hlp" 
   CommonDialog1.HelpCommand = cdlHelpContents 
End Sub 
For more details on how to use ShowHelp, highlight the text  HelpContext  in VB6 source code and then press  F1  and select  MsComDlg .

Custom Dialogs

Many of the Message Box, Input Box or the Common Dialogs format is not appropriate for situations programming. In the event that you can use a normal form to make a Dialog house plants, garden leaves. It takes quite a bit more work, but first it has the same color as other Forms in the program, and secondly we want to do anything you want. The only disadvantage is that the program will use more resources, to be frank is a little more memory.

Here we try to develop a generalized Login Form, can be used in many cases. On startup, this program will display a Login form requires users type in a username and password. Then, if a valid username and password, then the main form of the new program appears. How is the program we made a start with  Sub Main  in. BAS module. Sub Main calls the  Sub GetUserInfo  (also in the same module) to display the form frmLogin in Modal mode so it works the same way as the Message Box, Input Box or Common Dialogs.

Once the form frmLogin hidden by the execution of the statement Me.Hide SubGetUserInfo will continue to detail and fill in the textboxes txtUserName txtPasswordreturned and local variables strUserName strPassword. Source of the Sub Main andSub GetUserInfo are listed below:

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" 
      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 is displayed as below:

After users enter information and click  OK , it is only temporary display a message to confirm the details he. 

In the future, you can write code to check the name and password are not valid. There are a few details about its form frmLogin to work just like a Common Dialog:
  • Ta for the BorderStyle property is frmLogin Fixed Dialog.
  • Property of the textbox we PasswordChar txtPassword with "*" as the user to enter a password, I just saw a row of asterisks.
  • It is of the form is CenterScreen StartupPosition Property.
  • Default property of True cmdOK button to the user pressing the Enter key in forms isconsidered equivalent to cmdOK click button..
  • Similar way,  Property Cancel  button of  cmdCancel  is True the user to press  Esc  in the form is considered equivalent to cmdCancel click button.
Provisional coding of the event and click the cmdOK cmdCancel simply as listed below:

Private Sub CmdCancel_Click() 
   ' Clear txtUserName and txtPassword
   txtUserName = "" 
   txtPassword = "" 
   ' Hide the Form to get out of Modal mode
End Sub 

Private Sub CmdOK_Click() 
   ' Hide the Form to get out of Modal mode
End Sub 
You can download the source code of this program CustomDialog.


Post a Comment