Graphical User Interface (GUI)

Tips >> Visual Basic

MAKE WEB APPLICATION WITHOUT KNOWLEDGE OF CODING? CLICK HERE

Properties:

The properties describe the appearance of the GUI component. When adding a component, the Name property should be set immediately, according to the three-letter mnemonic naming conventions. The properties are displayed in the Properties Window in Name/Value pairs in alphabetical order.

Event Procedures:

An event procedure is a piece of code that responds to events that can occur for that object. Most of the events are generated by the user, enabling them to dictate the order of execution.

Forms:

The Form is the main stage of your application. By default, the Standard Exe option starts with a form called "Form1". The Name property of the Form should be named with a three-letter mnemonic prefix of "frm". Each Form will be a Window in your application. Controls are added to the form by either double-clicking them in the toolbox, or by selecting the control and drawing a bounding rectangle on the form. Your application may use more than one form.

To add a new Form to the project, either select "Add Form" from the "Project" menu or right-click the Forms folder in the Project Explorer and select, "Add", and then "Form".

To load a new form, use the Show method. The parameter, vbModal, is optional. If used, vbModal means that the form has focus until closed within the application.

Private Sub cmdDisplay_Click()
     frmResults.Show vbModal
End Sub

The Load command can be used to load a form without showing it. This technique is useful if you want to preload a form, and then use either the "Show" or "Visible" method to make it visible as and when required.

Standard Controls:

Controls are added to the Form from the Toolbox. Each control has a set of properties, and a set of event procedures associated with it. The following lists the control, reading left to right, top to bottom as they appear in the standard Toolbox.

  1. Pointer.
  2. PictureBox Control.
  3. Label Control.
  4. TextBox Control.
  5. Frame Control.
  6. CommandButton Control.
  7. CheckBox Control.
  8. OptionButton Control.
  9. ComboBox Control.
  10. ListBox Control.
  11. Horizontal and Vertical Scroll bars.
  12. Timer Control.
  13. DriveListBox, DirListBox, and FileListBox.
  14. Shape Control.
  15. Line Control.
  16. Image Control.
  17. Data Control.
  18. Object Linkking and Embedding (OLE) Control.

The Pointer:

The Pointer is not a control, but is used to interact with the controls on the form, allowing you to move and resize them. The Pointer is selected by default. When a control is added to the form, the focus reverts back to the Pointer.

PictureBox Control:

The PictureBox is used to display images or act as a container to other controls. The three-letter mnemonic for a PictureBox is pic (eg. picFace). The main event for a PictureBox is the Click event. Pictures are loaded into the PictureBox using the LoadPicture function. The following example toggles between face0.gif and face1.gif with each click of the mouse.

Private Sub picFace_Click()
     Static toggle As Integer
     Dim strFileName As String
     strFileName = "c:\images\face" & toggle & ".gif"
     picFace.Picture = LoadPicture(strFileName)
     toggle = toggle Xor 1
     End Sub

Animated GIFs aren't supported with Visual Basic 6, but are supported in VB.Net.

Label Control:

The Label control is used to display text that can't be changed directly by the user. Labels are more commonly used to place captions against other controls or store calculated values. The three-letter mnemonic for a Label is lbl (eg. lblPrompt).

The default property of a Label is Caption. The Caption property may be set at design-time using the Properties Window, and changed at run-time.

lblPrompt.Caption = "Changed at run-time"

Note: In VB.Net, the Caption property has been dropped in favour of the Text property for consistency.

TextBox Control:

The TextBox is used to display text that may be edited directly by the user. The three-letter mnemonic for a TextBox is txt (eg. txtData). The default event for a TextBox is "Change", and the default property is "Text". The following example allows the enter key to be used to tab to the next control in the tab order.

Private Sub txtData_KeyDown(KeyCode As Integer, Shift As Integer)
     ' Check for a carriage return
     If KeyCode = 13 Then
          ' Turn off the beep and tab to the next focusable control
          KeyCode = 0
          SendKeys "{TAB}"
     End If
End Sub

To allow text on more than one line, the Multiline Property must be set to True. If the ScrollBars Property doesn't allow a Horizontal ScrollBar, then the text will wrap.

The length of the Text property is limited to 2048 characters for a TextBox, and about 32K if the MultiLine property is set to True.

Frame Control:

The Frame control is used to group controls and provides a means of sub-dividing the Form visually. The three-letter mnemonic for a Frame is fra (eg. fraPaymentMethod). The default property is Caption, which can be used to give context to the grouping (eg. Payment Method).

Controls should be drawn within the Frame in order to be associated with the Frame. When the control is associated, moving the Frame also moves all of the associated controls. When option buttons are used, only one may be selected on the Form. Option Buttons placed in a Frame are associated with the Frame, and are treated as a new group.

CommandButton Control:

The CommandButton is used by the user to invoke some action. The three-letter mnemonic for a CommandButton is cmd (eg. cmdQuit). The default event for a CommandButton is "Click". The following example uses a CommandButton to end the program.

Private Sub cmdQuit_Click()
     Dim response As Integer
     response = MsgBox("Are you sure", vbQuestion + vbYesNo, "Quit"
     If response = vbYes Then
          End
     End If
End Sub

CheckBox Control:

The CheckBox control is used to give the user a choice of yes/no multiple choice options. The three-letter mnemonic for a CheckBox is chk (eg. chkHobbies). The "Value" property may be used to determine whether an item has been selected - a value of 1 indicates true, and a value of 0 indicates false. The following example uses a command button to determine which items have been selected from a control array of CheckBoxes.

Private Sub cmdList_Click()
     Dim counter As Integer
     Dim strMsg As String
     For counter = 0 To chkHobbies.UBound
          If chkHobbies(counter).Value = 1 Then
               strMsg = strMsg & chkHobbies(counter).Caption & vbCrL
          End If
     Next counter
     MsgBox strMsg, vbInformation, "Selected Items"
End Sub

OptionButton Control:

The OptionButton control is used to group options where the user can only select only one. As only one item may be selected OptionButtons are grouped in containers such as the Form, Frame or PictureBox. The three-letter mnemonic for an OptionButton is opt (eg. optPaymentMethod). The "Value" property may be used to determine whether an item has been selected - either True or False. The following example uses a CommandButton to determine which item has been selected from a control array of OptionButtons.

Private Sub cmdPayment_Click()
     Dim counter As Integer, selectedItem As Integer
     Dim strMsg As String
     For counter = 0 To optPaymentMethod.UBound
          If optPaymentMethod(counter).Value = True Then
               selectedItem = counter
          End If
     Next counter
     strMsg = optPaymentMethod(selectedItem).Caption
     MsgBox strMsg, vbInformation, "Selected Payment Method"
End Sub

ComboBox Control:

The ComboBox is a combination of a TextBox and a ListBox control. Items may be added to the list at design-time using the "List" property (<CTRL>+<ENTER> takes you to the next line to add a new item). Items may be added to the list at run-time using the AddItem method, and removed at run-time using the RemoveItem method (see below for details). The "Clear" method removes all items from the list. The three-letter mnemonic for a ComboBox is cbo (eg. cboArtist). The "Style" property determines which type of ComboBox is displayed from a choice of three.

ComboBox Style Property:

 

Value Constant Description
0
vbComboDropDown
A TextBox with an arrow to produce a dropdown list
1
vbComboSimple
A TextBox with a ListBox always displayed beneath
2
vbComboDrop-DownList
Restricts items in the TextBox to those in the list
The following example produces a MessageBox when a new item has been selected from the list.
Private Sub cboArtist_Click()
     MsgBox cboArtist.Text, vbInformation, "Selected Item"
End Sub

The AddItem Method:

The AddItem method is used to add items to either a ComboBox or a ListBox. The AddItem method has no effect if the ComboBox or ListBox is bound to a Data control. The AddItem method takes two parameters, "name", and "Index", where Index is an optional parameter. The following adds, "Garbage", to the end of the list, or to its correct sorted position of the Sorted Property has been set to True.

cboArtist.AddItem "Garbage"
The following example adds the item, "Blur", to position 3 within the list. The Sorted Property must be set to False if you specify a position.
cboArtist.AddItem "Blur", 3
The following example loads three artists into a list at run-time.

Private Sub Form_Load()
     cboArtist.AddItem "Gorillaz"
     cboArtist.AddItem "JJ72"
     cboArtist.AddItem "Radiohead"
End Sub

The RemoveItem Method:

The RemoveItem method is used to remove items from either a ComboBox or a ListBox. The RemoveItem method takes one parameter to indicate which item is to be removed.

cboArtist.RemoveItem 0
removes the first item from the list. The RemoveItem method has no effect if the ComboBox or ListBox is bound to a Data control.

The individual items may be accessed using their index number to identify their position in the list. The following would display the fourth item in the list.

MsgBox cboArtist.List(3), vbInformation, "Artist"

ListBox Control:

The ListBox displays a list of items that may be selected by the user. If the number of items in the list exceeds the size of the list box, scroll bars are added automatically. Items may be added to the list at design-time using the "List" property (<CTRL>+<ENTER> takes you to the next line to add a new item. Items may be added to the list at run-time using the AddItem method, and removed at run-time using the RemoveItem method. Both AddItem, and RemoveItem work in the same way as described above for the ComboBox. The "Clear" method removes all items from the list. The three-letter mnemonic for a ListBox is lst (eg. lstArtist). The "Style" property may be used to add a CheckBox to each item in the list.

ListBox Style Property:

 

Value Constant Description
0
vbListBoxStandard A standard list
1
vbListBoxCheckbox A check box is added to each item in the list
The following example produces a MessageBox when a new item has been selected from the list.

Private Sub lstArtist_Click()
     Dim strMsg As String
     strMsg = lstArtist.List(lstArtist.ListIndex)
     MsgBox strMsg, vbInformation, "Selected Item"
End Sub
Like the ComboBox, individual items may be accessed using their index number to identify their position in the list. The ListIndex property maybe used to determine which element in the list currently has focus. The following would display the item clicked in the list.
Private Sub lstArtist_Click()
     MsgBox lstArtist.List(lstArtist.ListIndex), vbInformation, "Artist
End Sub

HScroll and VScroll Control:

Scroll bars provide a convenient way of navigating through large amounts of information or providing a visual indication of a value. The Min and Max properties allow you to specify the minimum and maximum value of the scroll bar. The Value property indicates the position of the thumb of the scrollbar in relation to the Max and Min values. The SmallChange property specifies how much to increment or decrement the value if you click on the arrow, and the LargeChange property specifies how much to increment or decrement the value if you click on the track of the scroll bar. Visual Basic offers two scroll bars, a horizontal scroll bar (HScroll), and a vertical scroll bar (VSroll)

A VScrollBar is placed vertically on the form. The three-letter mnemonic for a VScrollBar is vsb (eg. vsbVolume). The default event for a scroll bar is the Change event.

A HScrollBar is placed horizontally on the form. The three-letter mnemonic for a HScrollBar is hsb (eg. hsbVolume). The default event for a scroll bar is the Change event. The following example uses a Label to show the exact value of the scroll bar.

Private Sub hsbVolume_Change()
     lblVolume = hsbVolume.Value
End Sub

Timer Control:

The Timer control is visible at design-time, but not shown at run-time. It is used for background processing at intervals specified by the Interval property. The Interval property takes an integer in the range 0 to 65,535. The Interval is measured in milliseconds, therefore a value of 1000 equals an interval of one second. An Interval of 0 disables the Timer control in VB 6, but not in VB.Net. To disable the Timer, set the Enabled Property to False. Setting it to True will enable it again.

The three-letter mnemonic for a Timer is tmr (eg. tmrMove). The default event for a Timer is the Timer event.

This example moves a PictureBox around the form. To try the example, add a PictureBox called picFace, and a Timer called tmrMove to the form. Set the Interval of the Timer to 1, and add a picture of a face to the PictureBox.

Private Sub tmrMove_Timer()
     Const distance As Integer = 50
     Static xDirection As Integer, yDirection As Integer
     ' The first time this function is called, the Static
     ' variables with have a value of 0
     If xDirection = 0 Then
          xDirection = 1
          yDirection = 1
     End If
     ' Move the picture around the form
     picFace.Move picFace.Left + distance * xDirection, picFace.Top + distance * yDirection
     ' Constrain to the form horizontally
     If picFace.Left < 0 Or picFace.Left + picFace.Width > Me.ScaleWidth Then
          xDirection = xDirection * -1
     End If
     ' Constrain to the form vertically
     If picFace.Top < 0 Or picFace.Top + picFace.Height > Me.ScaleHeight Then
          yDirection = yDirection * -1
     End If
End Sub

DriveListBox Control:

The DriveListBox allows the user to select a valid drive at run-time. This control is usually synchronised with the DirListBox and the FileListBox.

The three-letter mnemonic for a DriveListBox is drv (eg. drvList). The default event for a DriveListBox is the Change event. As the drive may not be ready to use, it is a good idea to use error trapping if synchronised with the DirListBox and FileListBox.

DirListBox Control:

The DirListBox displays a list of folders. This control is usually synchronised with the DriveListBox and the FileListBox.

The three-letter mnemonic for a DirListBox is dir (eg. dirList). The default event for a DirListBox is the Change event.

FileListBox Control:

The FileListBox displays a list of files. This control is usually synchronised with the DriveListBox and the DirListBox.

The three-letter mnemonic for a FileListBox is fil (eg. filList). The default event for a filListBox is the Click event.

The following properties are available for the FileListBox.

FileListBox Properties:

Property Description
Archive
A boolean value to indicate whether archive attributes are displayed (default: True).
Hidden
A boolean value to indicate whether hidden attributes are displayed (default: False).
Multiselect
An integer value to indicate whether multiple selection is allowed. The default is 0, meaning mutliselction is not allowed. A value of 1 indicates simple multi-selection. Multiple items are toggled on and off with a mouse click. A value of 2 indicates extended multi-selection. The Shift and Control keys may be used to select multiple items.
Pattern
A string that specifies the files to be displayed (eg. *.html).
ReadOnly
A boolean value to indicate whether read-only attributes are displayed (default: True)
System
A boolean value to indicate whether system attributes are displayed (default: False).
DriveListBox, DirListBox, and FileListBox Example
This example synchronises a DriveListBox, DirListBox and FileListBox. To try the example, add a DriveListBox and name it drvList, a DirListBox and name it dirList, and a FileListBox and name it filList.
Private Sub dirList_Change()
     filList.Path = dirList.Path
End Sub
Private Sub drvList_Change()
     On Error GoTo driveError
     dirList.Path = drvList.Drive
Exit Sub
driveError:
     MsgBox Err.Description, vbExclamation, "Drive Error"
End Sub
Private Sub filList_Click()
     Dim strFileName As String
     strFileName = filList.List(filList.ListIndex)
     MsgBox strFileName, vbInformation, "Selected File"
End Sub

Shape Control:

The Shape control is used to display a graphical shape. The shape is set at design-time, and the actual shape is determined by the Shape property and may be changed at run-time.

Shape Property:

 

Value Constant Description
0
vbShapeRectangle
Rectangle
1
vbShapeSquare
Square
2
vbShapeOval
Oval
3
vbShapeCircle
Circle
4
vbShapeRoundedRectangle
RoundedRectangle
5
vbShapeRoundedSquare
RoundedSquare
The three-letter mnemonic for a Shape is shp (eg. shpOutline). The following example changes a shape to an oval.
shpOutline.Shape = vbShapeOval

Note: The Shape control is not supported in VB.Net.

Line Control:

The Line control is used to display a line on a form. The line is visible even when the form's AutoRedraw property is set to False. The X1, X2, Y1 and Y2 properties may be used to move and resize the line at run-time.

The three-letter mnemonic for a Line is lin (eg. linDiagonal). The following example positions a line on the form from the top left corner to the bottom right corner.

Private Sub Form_Load()
     ' Top left corner
     linDiagonal.X1 = 0
     linDiagonal.Y1 = 0
     ' Bottom right corner
     linDiagonal.X2 = Me.ScaleWidth
     linDiagonal.Y2 = Me.ScaleHeight
End Sub

Note: The Line control is not supported in VB.Net.

Image Control:

The Image control is used to display a picture. It doesn't contain as many properties, methods and events as a PictureBox but repaints faster as it uses fewer system resources. The three-letter mnemonic for an Image is img (eg. imgFace). The following example loads a picture into an Image control.

imgFace.Picture = LoadPicture("c:\images\face.gif")

Visit Unisys and search the site for LZW for legal implications about using the Image control.

The Image control is not supported in VB.Net.

Data Control:

The Data control allows data-aware controls to be bound to Fields within a recordset, providing an efficient solution for accessing a database without writing any code. The Caption property will be the name displayed on the Data control. The DatabaseName property is used to store the location and name of the database. The RecordSource property is used to determine the name of the table or stored procedure in the database. The three-letter mnemonic for a Data control is dta (eg. dtaQuestion).

To bind a data-aware control to the Data control, set the DataSource property of the data-aware control to the name of the Data control (selected from a drop-down list). Having set the DataSource, you can select the DataField from a drop-down list on the data-aware control.

Object Linking and Embedding (OLE) Control:

The Object Linking and Embedding (OLE) control allows you to insert an insertable object into your application. When you add the control to your form, you will be given a list of insertable objects that can be created from new on your machine (eg. Paint Shop Pro) or you can select an object from an existing file such as a Word document.

The three-letter mnemonic for an OLE control is ole (eg. olePowerPointPresentation).

The OLE Control is not supported in VB.Net.

Menus:

Menus can be added to a form using the Menu Editor, selected from The "Tools" menu or from the button on the toolbar. Selecting a menu item at design-time takes you to the code editor for the specific menu item. VB.Net menus are written in-place.

The name is the identifier for the control. The three-letter mnemonic for a menu item is mnu (eg, mnuFile). I find it useful to name a sub menu with the first letter from the name of the menu on the level above. For example, a menu name for a File menu might be mnuFile. If I was to add a sub menu of Exit, I would name it mnuFExit so that in the code window all the menu items related to File were grouped together. All controls must be named uniquely.

The caption is the name the user sees on the menu. The & operator may be used to create a shortcut to a menu name. Whichever letter is preceded by an & will appear underlined. The menu item can then be accessed by the user by pressing and holding the Alt key and pressing the underlined letter. If a menu item had a caption of E&xit, the x would be underlined. The user can then use the Alt+x key combination to access that menu item. Separators may added to a menu with a caption of a single hyphen (-). You can have more than one separator, but they must be named uniquely.

Shortcuts may be assigned to menu items to make them accessible through a sequence of shortcuts. For example, most Windows applications use the sequence Ctrl+C to copy (With the control key pressed, hit the 'C' key on the keyboard).

Setting the shortcut Ctrl+Z against a "Zoom" menu item would mean that a user could access the "Zoom" menu item with Ctrl+Z as opposed to using the mouse and selecting the item from the menu.

Menu Item Control Array:

A menu item may be a control array. This is useful if the behaviour of menu items are similar. The menu items have the same name but are identified by different index numbers. The Index property is used to determine which item was selected in the menu item's Click event. The Index number does not effect the menu item's screen position.

The following example displays a picture depending on which menu item is selected.

Private Sub mnuPicture_Click(Index As Integer)
     Dim pictureName As String
     pictureName = "c:\viewer\images\face" & Index & ".jpg"
     picFace.Picture = LoadPicture(pictureName)
End Sub

MENU PROPERTIES:

The Checked property inserts a check mark by the side of the menu item. Check marks are used to indicate whether an item is on or off. If the Enabled check is removed, the menu item is dimmed and unable to receive events. If the Visible check is removed, the menu item is not visible to the user. The Window CheckBox is used if the menu control contains a list of MDI child forms.

The menu's arrow buttons may be used to move the menu items up and down, or promote/demote sub-menus. The left arrow demotes the menu item's level, and the right arrow promotes the menu item's level. You can have up to four levels of menus. The up arrow moves the menu item up within the current menu level, and the down arrow moves the menu item down within the current menu level.

The following example illustrates the use of menus with TextBoxes to create a simple application capable of Copy, Cut and Paste. The example uses a control array of TextBoxes called txtData.

Option Explicit
Private Sub mnuFCopy_Click()
          ' Copy the selected text to the Clipboard Object
     Clipboard.Clear
     Clipboard.SetText Screen.ActiveControl.SelText
End Sub
Private Sub mnuFCut_Click()
     ' Copy the selected text to the Clipboard Object and remove
     ' the selected text
     Clipboard.Clear
     Clipboard.SetText Screen.ActiveControl.SelText
     Screen.ActiveControl.SelText = ""
End Sub
Private Sub mnuFExit_Click()
     Unload Me
End Sub
Private Sub mnuFPaste_Click()
     ' Paste the contents of the Clipboard to the Selection
     Screen.ActiveControl.SelText = Clipboard.GetText
End Sub
Private Sub txtData_GotFocus(Index As Integer)
     txtData(Index).SelStart = 0
     txtData(Index).SelLength = Len(txtData(Index).Text)
End Sub
 

 

If you don't find what you are looking for. Please click here to submit your query, our experts will reply soon.

 

E-mail : sales@virtualsplat.com
Phone : +91-9892413501

Whatsapp Icon +91-9967648641

Whatsapp Icon +91-9967648641