Introduction
Menus are vital to any application. Depending on the program, the menus enable the user to physically use your program. The user chooses whichever menu and the program responds accordingly—whether it is showing a dialog box, or changing the color of the words, or exiting.
Menus
Menus allow you to arrange commands in a logical and easy-to-find fashion. A menu shouldn’t contain paragraphs of text, or even long sentences; its sole purpose is to help you navigate through the entire program.
Application Standardization
You may have noticed that the various products in Microsoft’s Office Suite have similar menus; this is true with many other software packages. This standardization technique is pivotal, because it enables the application’s user to learn other applications quickly.
Application Standardization includes the structure of your toolbars, menus, and overall look and feel of your applications. All Windows applications look similar, and yours should be designed to enable the users to learn the application quickly. For example: Most Windows applications have a File menu dealing with file-oriented tasks. Imagine how difficult it would be for a new user to figure out that you have put your printing functionality under a menu called, for example, Technical Tasks -> Hardware -> Printers -> Print.
Our Project
Open Visual Studio and create a new Visual Basic Windows Forms project. Name it anything you like. Add another form to the project so that you have two forms. Add the following objects to Form1:
- MenuStrip
- ContextMenuStrip
- OpenFileDialog
- SaveFileDialog
I have kept the default names, but you are welcome to rename them; just keep that in mind when we code.
Creating a Menu
- Click the MenuEditor component at the bottom of the screen. This will allow you to start entering menu items. Type in Fileand press Enter.
You now have a File menu!
- Click File, then underneath File where it displays text, as shown in Figure 1, type Open.
Figure 1: Type Here - Repeat the steps to enter the Save, Recent, and Exit items to the File menu.
- Add a menu item ‘Edit’ next to File and Add Cut, Copy, and Paste underneath it.
- Add a Help menu with About, and Online items.
Now that you have the main menu sorted, let’s take it a step further and add a submenu to the Open menu item. To do this, follow these steps:
- Click the Open menu item.
- To the right of the Open menu item, you should see the ‘Type Here’ section.
- Enter Text.
- Underneath the Text menu item, enter Other (see Figure 2).
Figure 2: Example Menu items
Adding Menu Features
Currently, the menus look a bit, well, dull. Let’s add some small but significant changes to the menus.
Adding Alt Key Shortcuts
If you do not know what an Alt key shortcut key is, let me explain: An Alt key shortcut enables you to press the Alt key and then the underlined letter to display the menu. For example: If you press Alt + F, it should open the File menu. To make a letter in the menu display underlined and act as an Alt key shortcut, follow these steps:
- Click the desired Menu item.
- Open the Properties Window.
- Add an ampersand in front of the desired letter to be used as a shortcut. In Figure 3, I have added an ampersand in front of the O in Open.
Figure 3: Alt key shortcut added to Open menu
Adding Keyboard Shortcut Keys to Menus
Shortcut keys are usually a combination of Ctrl and a letter. For example, Ctrl + C is the keyboard shortcut for Copy and Ctrl + V is the Keyboard shortcut for Paste. To add a keyboard shortcut key to a menu item, follow these steps:
- Click the desired Menu Item.
- Open the Properties Window.
- Find the Shortcut keys Property.
- Set the desired Shortcut, as displayed in Figure 4.
Figure 4: Adding Shortcut keys to the Cut Menu item
The Shortcut will be displayed next to the Menu item’s text.
Adding Icons to Menu Items
To add a small icon next to the Menu Item, follow these easy steps:
- Click the desired menu item.
- Open the Properties Window.
- Select the Icon Property.
Once you click on the button, the Select Resource box will appear. Here, you can select from already added icons inside your project, or add new items to your project’s resources (see Figure 5):
Figure 5: Selecting an Icon for a Menu Item
Adding a Separator Bar Inside the Menu
To Add a Separator bar to your menu, follow these steps:
- Click the Menu Item that you want to separate from other menu items.
- When the ‘Type Here’ text appears, look closely. There is a small drop-down arrow next to it, as shown in Figure 2.
- Select Separator from the displayed list.
Your finished Menus should look like those shown in Figures 6-8.
Figure 6: File Menu
Figure 7: Edit Menu
Figure 8: Help Menu
In case this article isn’t long enough already, I have added some basic code…
Opening Files
Add the following Namespace and code to make use of the OpenFileDialog to open a file. The code is slightly different for the Text and Other file types (according to the menus):
Imports System.IO Private Sub TextToolStripMenuItem_Click(sender As Object, _ e As EventArgs) Handles TextToolStripMenuItem.Click OpenFileDialog1.Filter = "*.txt|*.txt" If OpenFileDialog1.ShowDialog = DialogResult.OK Then OpenFile(OpenFileDialog1.FileName) End If End Sub Private Sub OpenFile(strFileName As String) Dim srStream As New StreamReader(strFileName) TextBox1.Text = srStream.ReadToEnd srStream.Close() End Sub Private Sub OtherToolStripMenuItem_Click(sender As Object, _ e As EventArgs) Handles OtherToolStripMenuItem.Click OpenFileDialog1.Filter = "*.*|*.*" If OpenFileDialog1.ShowDialog = DialogResult.OK Then OpenFile(OpenFileDialog1.FileName) End If End Sub
I set the Filters for the OpenFileDialog according to which option was selected, and then make use of the Open sub to open the selected file.
Saving a File
Add the following code to save a file:
Private Sub SaveToolStripMenuItem_Click(sender As Object, _ e As EventArgs) Handles SaveToolStripMenuItem.Click SaveFileDialog1.Filter = "TXT Files (*.txt*)|*.txt" If SaveFileDialog1.ShowDialog = _ Windows.Forms.DialogResult.OK Then My.Computer.FileSystem.WriteAllText _ (SaveFileDialog1.FileName, TextBox1.Text, True) End If End Sub
When the Save Menu item is clicked, a SaveFileDialog opens and writes the content of the Textbox into a filename supplied by the user.
Cut, Copy, and Paste
Add the following code to be able to Cut, Copy, and Paste text:
Private Sub CopyToolStripMenuItem_Click(sender As Object, _ e As EventArgs) Handles CopyToolStripMenuItem.Click Clipboard.SetText(TextBox1.SelectedText) End Sub Private Sub CutToolStripMenuItem_Click(sender As Object, _ e As EventArgs) Handles CutToolStripMenuItem.Click Clipboard.SetText(TextBox1.SelectedText) TextBox1.SelectedText = "" End Sub Private Sub PasteToolStripMenuItem_Click(sender As Object, _ e As EventArgs) Handles PasteToolStripMenuItem.Click TextBox1.SelectedText = Clipboard.GetText End Sub
Adding a Recently Used List
To create an MRU list, you need to save the current file’s name and location either inside the Windows Registry, a Configuration file, or an ordinary Text file, as I have done.
In this example, I have made use of a file named Recent.txt that is saved inside the Bin folder of my application. The contents of this file get read into a Queue object and populate the list. In saving the MRU list, I have made use of a Queue object to save it into the file named Recent.txt. Here is the code:
Dim MRUlist As Queue(Of String) = _ New Queue(Of String)() Private Sub SaveRecentFile(strPath As String) RecentToolStripMenuItem.DropDownItems.Clear() LoadRecentList() If Not (MRUlist.Contains(strPath)) Then MRUlist.Enqueue(strPath) End If While MRUlist.Count > 5 MRUlist.Dequeue() End While For Each strItem As String In MRUlist Dim tsRecent As New ToolStripMenuItem(strItem, Nothing) RecentToolStripMenuItem.DropDownItems.Add(tsRecent) Next Dim stringToWrite As New StreamWriter _ (System.Environment.CurrentDirectory + "\Recent.txt") For Each item As String In MRUlist stringToWrite.WriteLine(item) Next stringToWrite.Flush() stringToWrite.Close() End Sub Private Sub LoadRecentList() MRUlist.Clear() Try Dim srStream As New StreamReader _ (System.Environment.CurrentDirectory + "\Recent.txt") Dim strLine As String While (InlineAssignHelper(strLine, srStream.ReadLine())) _ IsNot Nothing MRUlist.Enqueue(strLine) End While srStream.Close() Catch ex As Exception MessageBox.Show("Error") End Try End Sub Private Shared Function InlineAssignHelper(Of T) _ (ByRef target As T, ByVal value As T) As T target = value Return value End Function Private Sub RecentFile_click(sender As Object, _ e As EventArgs) End Sub Private Sub Form1_Load(sender As Object, e As EventArgs) _ Handles Me.Load LoadRecentList() For Each item As String In MRUlist Dim fileRecent As New ToolStripMenuItem(item, Nothing, _ RecentFile_click()) RecentToolStripMenuItem.DropDownItems.Add(fileRecent) Next End Sub Private Function RecentFile_click() As System.EventHandler End Function
Dynamically Creating Menus
Add the following code to show the second form:
Private Sub AboutToolStripMenuItem_Click(sender As Object, _ e As EventArgs) Handles _ AboutToolStripMenuItem.Click Dim f2 As Form2 = New Form2() f2.Show() End Sub
Add the following code inside Form2 to dynamically add menus onto Form2:
Public Class Form2 Private Sub MergeMenus() Dim mmMain As New MainMenu() Dim mmMenuToAdd As New MainMenu() Dim miItem1 As New MenuItem() Dim miItem2 As New MenuItem() miItem1.Text = "File" miItem2.Text = "Edit" mmMain.MenuItems.Add(miItem1) mmMenuToAdd.MenuItems.Add(miItem2) mmMain.MergeMenu(mmMenuToAdd) Me.Menu = mmMain End Sub Private Sub Form2_Load(sender As Object, e As EventArgs) _ Handles MyBase.Load MergeMenus() End Sub End Class
This code creates two MainMenu objects and Merges them upon Form_Load.
Conclusion
Menus can be very powerful. Knowing how to use menus in Visual Basic is a crucial skill any developer should have.