Menu controls expose only one event, Click. As you expect, this event fires
when the user clicks on the menu:
Private Sub mnuFileExit_Click()
You can manipulate menu items at run time through their Checked, Visible, and
Enabled properties. For example, you can easily implement a menu item that acts
as a switch and displays or hides a status bar:
Private Sub mnuViewStatus_Click()
' First, add or remove the check sign.
mnuViewStatus.Checked = Not mnuViewStatus.Checked
' Then make the status bar visible or not.
staStatusBar.Visible = mnuViewStatus.Checked
While menu items can be responsible for their own Checked status, you usually
set their Visible and Enabled properties in another region of the code. You make
a menu item invisible or disabled when you want to make the corresponding command
unavailable to the user. You can choose from two different strategies to achieve
this goal: You can set the menu properties as soon as something happens that affects
that menu command, or you can set them one instant before the menu is dropped
down. Let me explain these strategies with two examples.
Let's say that the Save command from the File menu should look disabled if
your application has loaded a read-only file. In this case, the most obvious place
in code to set the menu Enabled property to False is in the procedure that loads
the file, as shown in the code below.
Private Sub LoadDataFile(filename As String)
' Load the file in the program.
' ... (code omitted)...
' Enable or disable the menu enabled state according to the file's
' read-only attribute (no need for an If...Else block).
mnuFileSave.Enabled = (GetAttr(filename) And vbReadOnly)
This solution makes sense because the menu state doesn't change often. By comparison,
the state of most of the commands in a typical Edit menu (Copy, Cut, Clear, Undo,
and so on) depends on whether any text is currently selected in the active control.
In this case, changing the menu state any time a condition changes (because the
user selects or deselects text in the active control, for example) is a waste
of time, and it also requires a lot of code. Therefore, it's preferable to set
the state of those menu commands in the parent menu's Click event just before
displaying the menu:
Private Sub mnuEdit_Click()
' The user has clicked on the Edit menu,
' but the menu hasn't dropped down yet.
On Error Resume Next
' Error handling is necessary because we don't know if
' the Active control actually supports these properties.
mnuEditCopy.Enabled = (ActiveControl.SelText <> "")
mnuEditCut.Enabled = (ActiveControl.SelText <> "")
mnuEditClear.Enabled = (ActiveControl.SelText <> "")
More in Menus in Visual Basic 6