Visual Basic - Menus and Advanced Controls
With this article, we tend to look higher with/in Visual Basic. This article introduces to the reader, the method to introduce menu system, and some advanced controls like Rich TextBox, Toolbar, Status Bar and Progress Bar.
Menu System
In almost all the applications the menu system is used to navigate through the software and to access the features in the software. The menu system is not visible in the ToolBox and is rather available in Tools Menu or can be directly called by CTRL E. The menu editor appears as shown in Figure 1.
Figure 1: Microsoft Visual Basic Menu Editor
As shown above the Caption (one which will be visible on the screen) in &Bold and the Name is mnuBold. The shortcut to access the menu is CTRL B.
Private Sub mnuBold_Click()
text1.FontBold = True ‘ code for making the text bold
End Sub
This menu appears as shown in Figure 2.
Figure 2: Menu Created through Visual Basic.
The options Bold, Italics and Underline are indented and are accessible under the top level menu Font. The shortcuts of the entire menu are displayed on the right. These shortcuts can not be assigned to top level menu (here Format or Font, as they have child menu under them.)
The Next Button is used to add a new menu item. Insert Button is used to add a menu item between two existing menus. The left arrow indents a menu item, while the right arrow does the reverse. The Up and Down arrows are used to move the currently selected item.
Some menu items can be disabled by removing the Tick from the Enabled CheckBox. Similarly they can be made visible or can be provided by the tick by the option sown in Figure 1.
To add separator
As visible in Figure 2, there’s a separator between Font and Bullets. To include the separator, we set the caption to “-“, as shown in figure 1. We can create an array of separators by keeping the name as mnuLine and setting different values of Index.
Adding a Pre-defined Menu
Visual Basic provides us inbuilt facility of pre-defined menus. This makes our programming easier and faster. To view the ready-to-do menus, we open Visual Component Manager from View Menu. We select the Menus from the different Templates available to us. Let’s try selecting File Menu and see what happens. On double clicking on File Menu, a new menu is added to our project. However the code for this menu needs to be written by us.
Figure 3: Visual Component Manager
Adding a Pop-Up Menu
Pop-Up menus are those menu’s that appear when we right click on the Visual Basic form. To create such a menu, we first create a menu through Menu Editor and then keep its visibility OFF. Thereafter, we write a code in the object code window as shown below.
Private Sub Form_MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single)
If Button = vbRightButton Then ‘For Right Button
PopupMenu mnuEdit
End If
End Sub
Figure 4: Pop-Up Menu
Similarly we can add menu’s for left button and middle button by using constants; vbLeftButton or vbMiddleButton instead of vbRightButton.
Adding or Removing Menu Items while Runtime.
We can add or delete menu items dynamically by using Load and Unload functions. Before this, we need to make a controlled array of the item to which we need to add/remove the menu. We initially assign the Index as 0 and visible as False as shown in Figure 5.
Figure 5: Designing Extendable Menu’s
The code is written as below:
Dim i As Integer
Private Sub cmdAdd_Click()
Load mnuFileItem(i)
mnuFileItem(i).Caption = "New Item" & Str(i)
mnuFileItem(i).Visible = True
i = i + 1
End Sub
Private Sub cmdRemove_Click()
Load mnuFileItem(i)
mnuFileItem(i).Caption = "New Item" & Str(i)
mnuFileItem(i).Visible = True
i = i + 1
End Sub
Private Sub Form_Load()
i = 1
End Sub
Advanced Controls
Rich TextBox
The TextBox doesn’t provide us with facilities of formatting the selected text. The whole of the text gets formatted which is not intended. The Rich TextBox can be added through Components option in Project Menu and selecting Microsoft Rich TextBox Control. This TextBox appears similar to a normal TextBox but has some additional properties, which renders us various other formatting facilities which will be dealt in later sections.
Figure 6: RTB Demonstration
Table 1: RTB Features
Feature |
Property/ Code |
||||||
Alignment |
SelAlignment Property assumes three values: rtfLeft for Left Alignment (default), rtfCenter and rtfRight for Center and Right Alignment. |
||||||
Bullets |
SelBullet Property when set to true inserts bullet to the selected text. The indent to be provided is set by BulletIndent property. |
||||||
Superscript and Subscript |
SelCharOffset Property accepts a positive integer value to Superscript a text and a negative integer to Subscript the selected text. |
||||||
Bold, Italics, Underline, StrikeThru |
The properties SelBold, SelItalic, SelUnderline, SelStrikeThru when set to True do the formatting of the selected text accordingly. |
||||||
Searching and Replacing |
The Find Method accepts the text to be searched as an argument and finds out the text in the Rich TextBox. To replace the text searched, we set SelRTF property as the new text. |
||||||
Open A File |
FileName property is used to the file whose contents are to be displayed in the RTB. |
||||||
Save File |
SaveFile Method has filename as first argument and type of file as the second argument. There are two types of file:
|
The above commands are illustrated in the program code written below,
‘Code for Alignment
Private Sub cmdLeft_Click()
rtxtText.SelAlignment = rtfLeft ‘Align to Left
End Sub
Private Sub cmdCenter_Click()
rtxtText.SelAlignment = rtfCenter ‘Align to Center
End Sub
Private Sub cmdRight_Click()
rtxtText.SelAlignment = rtfRight ‘Align to Right
End Sub
‘Adding Bullets
Private Sub cmdBullets_Click()
rtxtText.BulletIndent = 50 ‘Bullet Indent set to 50
rtxtText.SelBullet = True ‘Give a bullet.
End Sub
‘Subscript and Superscript
Private Sub cmdSubScript_Click()
rtxtText.SelCharOffset = -60 ‘Lower the letter
rtxtText.SelFontSize = rtxtText.SelFontSize – 1 ‘Decrease the font size
End Sub
Private Sub cmdSuperScript_Click()
rtxtText.SelCharOffset = 40 ‘Raise the letter
rtxtText.SelFontSize = rtxtText.SelFontSize – 1 ‘Decrease the font size
End Sub
‘Formatting
Private Sub cmdBold_Click()
If rtxtText.SelBold = False Then
rtxtText.SelBold = True
Else
rtxtText.SelBold = False
End If
End Sub
Private Sub cmdItalics_Click()
If rtxtText.SelItalic = False Then
rtxtText.SelItalic = True
Else
rtxtText.SelItalic = False
End If
End Sub
Private Sub cmdStrikethrough_Click()
If rtxtText.SelStrikeThru = False Then
rtxtText.SelStrikeThru = True
Else
rtxtText.SelStrikeThru = False
End If
End Sub
Private Sub cmdUnderline_Click()
If rtxtText.SelUnderlined = False Then
rtxtText.SelUnderlined = True
Else
rtxtText.SelUnderlined = False
End If
End Sub
‘Search and Replace
Private Sub cmdSearch_Click()
rtxtText.SelStart = rtxtText.Find(txtSearch.Text)‘Find the text
rtxtText.SelUnderline = True ‘Underline the text
End Sub
Private Sub cmdReplace_Click()
rtxtText.Find (txtSearch.Text) ‘Search the text
rtxtText.SelRTF = txtReplace.Text ‘Replace the searched text
End Sub
‘Open, Save and Print
Private Sub cmdOpen_Click()
rtxtText.FileName = "c:\data.txt" ‘Opens the file data.txt
End Sub
Private Sub cmdSave_Click()
Dim file as String
file = InputBox("Enter FileName") ‘Input filename from user
If MsgBox("Do you want to save in RTF format", _
vbYesNo) = vbYes Then
rtxtText.SaveFile (file),rtfRTF ‘Save in RTF format
Else
rtxtText.SaveFile (file),rtfText ‘Save in Notepad format
End If
End Sub
Private Sub cmdPrint_Click()
Printer.NewPage ‘Create a new page on printer.
rtxtText.SelText = rtxtText.Text ‘Select entire text of the TextBox
rtxtText.SelPrint (Printer.hDC) ‘Print it on the printer
End Sub
Toolbar
There are some commonly used controls in Windows like Toolbars, Status Bar, Progress Bar. These controls are available in Microsoft Windows Common Controls, which can be accessed through Components in Project Menu.
Figure 7: Common Controls |
We can add different toolbars to the form. After pasting the toolbar on the form, we need to right click on it to access the properties.
On the Button Tab in the properties, we can insert the Buttons as shown in Figure 8.
Figure 8: Addition of Buttons
The code when the button is clicked is to be written in,
Private Sub Toolbar1_ButtonClick(ByVal Button_ End Sub
Pictures can also be added using Image Property mentioned under General Tab |
Figure 9: Rich TextBox with toolbars |
Private Sub_ Toolbar1_ButtonClick(ByVal_ Button As ComctlLib.Button) If Button = "Bold" Then cmdBold_Click ElseIf Button = “Italics” then cmdItalics_Click End If |
There can be different types of buttons in a tool bar, which can be accessed by the Style Property under the Buttons Tab.
Table 2: Styles of toolbars
Style |
Description |
tbrCheck |
The ToolBar Button acts as a PushButton and remains pressed until re-pressed |
tbrButtonGroup |
Only one butoon of the entire group can be accessed. It acts as an Option Button |
tbrSeperator |
It provides an aesthetic appearance by providing a separator in between the two Buttons |
tbrPlaceHolder |
Provides a ComboBox in the Tool Bar. The width should be mentioned in the Button Tab so that a proper space is left between the two buttons. Thereafter, a combo box should be placed externally. |
A toolbar can be added dynamically while run-time by the following method.
|
Dim i As Integer
Private Sub cmdAdd_Click() Dim button1 As Button Set button1= _ Toolbar1.Buttons.Add() button1.Style = tbrDefault button1.Caption = txtText.Text End Sub
|
Status Bar
The status bar is sometimes used as mini-help for application. This bar is used to show the status of an operation and hence it is named as Status Bar. We can add Panels to the collection by right clicking on the status bar and accessing the properties. The text to be displayed in Panels can be coded as,
Private Sub Form_Load()
StatusBar1.Panels(1).Text = "Form Loaded"
End Sub
The status bar can display various pre-defined texts such as date, time and key status as per the Style defined:
Table 3: Styles of Status Bars
Style |
Text displayed |
sbrText |
For normal text or picture |
sbrCaps |
Caps Lock Status |
sbrNum |
Num Lock Status |
sbrIns |
Insert Status |
sbrScrl |
Scroll Lock Status |
sbrTime |
Current Time |
sbrDate |
Date |
Similarly, we can have Raised, Bevel or Inset appearances of the status bar which can be set through the Appearance property.
Figure 11: Property of StatusBar
The events can be called when the user clicks on any panel of the status bar. Each Panel has a unique key and with this key, one can code as shown below:
Private Sub StatusBar1_PanelClick(ByVal Panel As ComctlLib.Panel)
Select Case Panel.Key
Case "status" ‘first Panel with Key status
Panel.Text = "hi"
End Select
End Sub
A sample code is shown below to display picture in the status bar.
Private Sub cmdPicture_Click()
StatusBar1.Panels(2).Picture = “c:\back.jpg”
End Sub
Progress Bar
A progress bar is used to show the progress of the process. We often see this type of progress bar in the applications such as Adobe Photoshop. The coding of the Progress Bar is similar to that of a slider. We decide the range of the Progress Bar by Min and Max Properties. The value of the Progress Bar is indicated by the Value Property. We normally associate the value of the Progress Bar with that of a Timer.
A sample code is shown below
Private Sub Timer1_Timer()
If ProgressBar1.Value < 100 Then
ProgressBar1.Value = ProgressBar1.Value + 10
‘ increase value of progress bar
Else
Timer1.Enabled = False ‘stop timer
MsgBox "Processing Done" ‘display that 100 % is done.
End If
End Sub
Figure 12: Progress Bar
The code can assume complicacies as per the process. We have shown one example of opening a file which has a progress bar which appears embedded inside a status bar.
Dim file As String
Private Sub cmdOpen_Click() file = "c:\data" rTemp.FileName = file Timer1.Interval = Len(rTemp.Text) Timer1.Enabled = True End Sub
Private Sub Timer1_Timer() If ProgressBar1.Value < 100 Then ProgressBar1.Value= ProgressBar1.Value_ StatusBar1.Panels(1).Text_ Else rtxtFile.Enabled = True rtxtFile.FileName = file Timer1.Enabled = False StatusBar1.Panels(1).Text = "Done" ProgressBar1.Visible = False End Sub |
Figure 13 (a): While processing
Figure 13(b): After processing. |
The other controls highlighted in the Figure 7 can be programmed easily with the knowledge of controls covered in this article. In our next articles, we shall cover the File Management and Database Management.
Note: This series was first published in DeveloperIQ and was co-authored by Puneet Ghanshani with Pranjali Bakeri in 2005-2006.