Académique Documents
Professionnel Documents
Culture Documents
The end result of Example 1 will be a form containing a menu with two top-level items, File and Help.
The File menu, shown below, will have the following level-two items below it: New, Open, Save, Save As, Print, and Exit. Note that separator bars appear above the Save, Print, and Exit items.
The Help menu contains just one level-two item below it, About.
To build a menu for use with your VB program, you use the Menu Editor, which appears as an icon in the toolbar of the VB IDE. It is the circled item in the screen shot below:
Alternatively, you can invoke the Menu Editor from the Tools menu item as shown below:
1. Start a new VB project and invoke the Menu Editor using either method shown above (click the Menu Editor toolbar icon or select the Menu Editor option from the Tools menu). The Menu Editor screen appears, as shown below:
2. For "Caption", type &File (by placing the ampersand to the left of the "F", we establish "F" as an access key for the File item it enables the user to drop down the File menu by keying "Alt+F" on the keyboard in addition to clicking the "File" item with the mouse).
3. Click the "right-arrow" button (shown circled below). A ellipsis (...) will appear as the next item in the menu list, indicating that this item is a level-two item (below "File").
For "Caption", type &New; for "Name", type mnuNew, and for "Shortcut", select Ctrl+N. By specifying a shortcut, you allow the user to access the associated menu item by pressing that key combination. So here, you are providing the user three ways of invoking the "New" function: (1) clicking File, then clicking New on the menu; (2) keying Alt+F,N (because we set up an access key for "N" by placing an ampersand to left of "N" in "New"); or (3) keying Ctrl+N. At this point, your Menu Editor screen should look like this:
4. For "Caption", type &Open; for "Name", type mnuOpen, and for "Shortcut", select Ctrl+O. Your Menu Editor screen should look like this:
5. For "Caption", type - (a hyphen), and for "Name", type mnuFileBar1. A single hyphen as the Caption for a menu item tells VB to create a separator bar at that location. Your Menu Editor screen should look like this:
6. For "Caption", type &Save; for "Name", type mnuSave, and for "Shortcut", select Ctrl+S. Your Menu Editor screen should look like this:
7. For "Caption", type Save &As ..., and for "Name", type mnuSaveAs. Your Menu Editor screen should look like this:
8. For "Caption", type -, and for "Name", type mnuFileBar2. Your Menu Editor screen should look like this:
9. For "Caption", type &Print;for "Name", type mnuPrint; and for "Shortcut", select Ctrl+P. Your Menu Editor screen should look like this:
10. For "Caption", type -; and for "Name", type mnuFileBar3. Your Menu Editor screen should look like this:
11. For "Caption", type E&xit, and for "Name", type mnuExit. Your Menu Editor screen should look like this:
12. Click the "left-arrow" button (shown circled below). The ellipsis (...) no longer appears, meaning we are back to the top-level items.
For "Caption", type &Help; and for "Name", type mnuHelp. Your Menu Editor screen should look like this:
13. Click the "right-arrow" button to create a level-two item below "Help". For "Caption", type &About; and for "Name", type mnuAbout. Your Menu Editor screen should look like this:
14. At this point, we are done creating our menu entries, so click the OK button. That will dismiss the menu editor and return focus to the VB IDE.
15. Back in the VB IDE, your form will now have a menu, based on what you have set up in the Menu Editor. If you click on a top-level menu item (File for example), the level-two menu will drop down:
16. Click on the New menu item. The code window for the mnuFileNew_Click event opens, as shown below. Note: Click is the only event that a menu item can respond to.
In thePlace mnuFileNew_Click event, place the code you want to execute when the user clicks the New menu item. Since this is just a demo, we will place a simple MsgBox statement in the event procedure:
17. Code similar MsgBox statements for the Open, Save, Save As, and Print menu items:
MsgBox "Code for 'Open' goes here.", vbInformation, "Menu Demo" End Sub
End Sub
MsgBox "Code for 'Save As' goes here.", vbInformation, "Menu Demo"
End Sub
End Sub
18. For the Exit menu item Click event, code the statement Unload Me.
Unload Me
End Sub
19. For the About menu item Click event, code as shown below:
MsgBox "Menu Demo" & vbCrLf _ & "Copyright " & Chr$(169) & " 2004 thevbprogrammer.com", , _ "About"
End Sub
20. Run the program. Note how the code executes when you click on the various menu items. Also test the use of the access keys (e.g., Alt+F, N) and shortcut keys (e.g., Ctrl-O).
EXAMPLE 2:
This example shows you how to create a popup menu (sometimes called a context menu or a rightclick menu).
1. Start a new VB project and place a label on the form. Name the label lblTestText. Set the Caption to Test Text.
2. Open the Menu Editor, and create a top-level item with a Caption value of PopUpFormat and the Name mnuPopuUpFormat. Also importantly uncheck the Visible checkbox (see the circled item below). In order for a menu to be a pop-up menu, it must be invisible.
3. Create the following level-two menu items below the PopUpFormat top-level menu. (When creating these level-two items, keep the Visible box checked.)
4. Click OK to save your changes. Note: When you return to the IDE, you will NOT see this menu on the form (remember it's a pop-up menu, and it will only be visible when invoked through code).
5. Code the lblTestText_MouseDown event as shown below. Note that the Button parameter is tested for vbRightButton as is conventional, we only want to pop up the menu if the user right-clicks on the label. If the user clicks the right mouse button, the PopupMenu statement is executed. It is this statement that makes the pop-up menu appear.
The full syntax for the PopupMenu method, from MSDN, is: object.PopupMenu menuname, flags, x, y, boldcommand The PopupMenu method syntax has these parts: Part object Menuname Flags Description Optional. An object expression that evaluates to an object in the Applies To list. If object is omitted, the form with the focus is assumed to be object. Required. The name of the pop-up menu to be displayed. The specified menu must have at least one submenu. Optional. A value or constant that specifies the location and behavior of a pop-up menu, described as follows: Constant (location) vbPopupMenuLeftAlign vbPopupMenuCenterAlign vbPopupMenuRightAlign Value 0 4 8 Description (Default) The left side of the pop-up menu is located at x. The pop-up menu is centered at x. The right side of the pop-up menu is located at x.
Value 0
vbPopupMenuRightButton
Description (Default) An item on the popup menu reacts to a mouse click only when you use the left mouse button. An item on the pop-up menu reacts to a mouse click when you use either the right or the left mouse button.
Note: To specify both a "location" constant and a "behavior" constant, add the two values together. For example:
X Y boldcommand
Optional. Specifies the x-coordinate where the pop-up menu is displayed. If omitted, the mouse coordinate is used. Optional. Specifies the y-coordinate where the pop-up menu is displayed. If omitted, the mouse coordinate is used. Optional. Specifies the name of a menu control in the pop-up menu to display its caption in bold text. If omitted, no controls in the pop-up menu appear in bold.
5. Code the mnuBold_Click event as shown below. Note that the Checked property of the menu item is used. When set to True, this causes a checkmark to appear to the left of the menu item. The Checked property is typically used as a toggle.
Private Sub mnuBold_Click() If mnuBold.Checked Then lblTestText.FontBold = False mnuBold.Checked = False Else lblTestText.FontBold = True mnuBold.Checked = True End If End Sub
6. Code the mnuItalic_Click and mnuUnderline_Click events in a similar fashion as shown below.
Private Sub mnuItalic_Click() If mnuItalic.Checked Then lblTestText.FontItalic = False mnuItalic.Checked = False Else lblTestText.FontItalic = True mnuItalic.Checked = True End If End Sub
Private Sub mnuUnderline_Click() If mnuUnderline.Checked Then lblTestText.FontUnderline = False mnuUnderline.Checked = False Else lblTestText.FontUnderline = True mnuUnderline.Checked = True End If End Sub
7. Run the program and check out the various options you have coded.
NOTES: If desired, you can have both a "regular" menu and as many pop-up menus as you want on the same form. Any top-level menu that has its Visible box checked in the Menu Editor will appear at the top of the form in the menu bar you create. Any top-level menu that has its Visible box unchecked in the Menu Editor will NOT appear at the top of the form in the menu bar, but can be used as a pop-up menu invoked with the PopupMenu method.
Comments
Fri, 09/10/2010 - 06:57 Anonymous (not verified)
reply
vb 6.0 problem
hey guys out there. i am preparing an application where i need to make menus. i know i can display menus through menu editor, and also i can open 'open dialogue box' through commondialoguebox. but i don't no how to open a file. plz guide me..
reply
reply
Effective Tutorial
This is very much helpful for beginners
reply
query
gdf i have a query about this chapter is that if i want to create the menu in other indian language like Marathi,Kannada then what are the steps to craete this or how i will get this type of menues.
reply
reply
yeah
Thanks for theh tut! Is there an way to add it to an textbox wihout you'll get the standard context box with : paste,check spelling and so... thx
reply
MDI Overview
This document introduces you to the concept of Multiple Document Interface (MDI) and how to create menus within an MDI application. You will learn to create an MDI application in Microsoft Visual Studio .NET and learn why you might want to use this type of interface. You will learn about child forms that are contained within the MDI application, and learn to create shortcut, or context-sensitive, menus. MDI is a popular interface because it allows you to have multiple documents (or forms) open in one application. Examples of MDI applications include Microsoft Word, Microsoft Excel, Microsoft PowerPoint, and even the Visual Studio integrated development environment itself. Each application consists of one (or more) parent windows, each containing an MDI client areathe area where the child forms (or documents) will be displayed. Code you write displays as many instances of each of the child forms that you want displayed, and each child form can only be displayed within the confines of the parent windowthis means you can't drag the child forms outside the MDI container. Figure 1 shows a basic MDI application in use.
Figure 1. Use MDI to open multiple windows and have them all contained within the parent area
Uses of MDI
You'll use MDI most often in applications where the user might like to have multiple forms or documents open concurrently. Word processing applications (like Microsoft Word), spreadsheet applications (like Microsoft
Excel), and project manager applications (like Microsoft Project) are all good candidates for MDI applications. MDI is also handy when you have a large application, and you want to provide a simple mechanism for closing all the child forms when the user exits the application.
All child forms are displayed within the MDI parent's client area. The client area is the area below the MDI parent's title bar, any menus, and any tool bars. Child forms can be moved and sized only within the MDI parent's client area. Child forms can be minimized and their icon will be displayed within the parent's client area. Child forms can be maximized within the parent's client area and the caption of the child form is appended to the caption of the MDI form. Windows automatically gives child forms that have their FormBorderStyle property set to a sizable border a default size. This size is based on the size of the MDI parent's client area. You can override this by setting the FormBorderStyle property of the child form to any of the fixed type of borders. Child forms cannot be displayed modally. The MDI form can be minimized and only one icon will be displayed on the desktop representing the MDI form and all of its children. If the MDI form is unloaded, all of the loaded children will also be unloaded.
Note The client area includes any usable area on the MDI form minus any toolbars or status bars that you may have added to the MDI form.
In this section, you will walk through the steps of creating a simple MDI application using Visual Studio .NET. To do this, you will create a new form that will be the MDI parent form. You will add some menus to this new form, and then you will load the product form from a menu as a child form.
Creating Menus
Your main form will require menus so that you can perform actions such as opening child forms, copying and pasting data, and arranging windows. Visual Studio .NET includes a new menu designer that makes creating and modifying menus a snap. To add menus to your MDI parent form 1. Double-click the MainMenu tool in the Toolbox window to add a new object named MainMenu1 to the form tray. Note Unlike the form designer in Visual Basic 6.0, the Visual Studio .NET form designer places controls that don't have a user interface at run time into a special area on the form designer: the form "tray". They're out of the way, and don't get buried underneath other controls. This is a real improvement! 2. At the top of the MDI parent form, click the box with Type Here in it and type &File. Tip Just as in Visual Basic 6.0, inserting an ampersand (&) into a menu caption displays the caption with an underscore under the following letter. Pressing Alt+<the letter> acts as a hotkey, activating the menu item. One thing to note: if you're using Windows 2000 or later, it's possible that the hotkeys won't show up underlined until you press the Alt key. This setting is buried in the Display applet within Control Panel. In the Display Properties dialog box, check the Effects page: the Hide keyboard navigation indicators until I use the Alt key option controls this behavior. 3. 4. Press Enter to move to the next menu item and type &Products. Press Enter to move to the next menu item and type a hyphen (-). Tip Rather than using the "-" to indicate a divider in the menu, you can insert the next menu item (Exit, in this case), and then right-click the new item. Select "Insert Separator" from the context menu, and Visual Studio .NET will insert a separator above the current item for you.
5.
You have now created the first drop-down menu on your main form. You should have something that looks like Figure 2.
Figure 2. The menu designer allows you to type your menu structure in a WYSIWYG fashion To the right of the File menu and at the same level, you'll see another small box with the text, Type Here. Click it and type the following menu items by pressing Enter after each one.
&Edit
Once more to the right of the Edit menu and at the same level, add the following menu items in the same manner.
mnuFile
mnuFProducts mnuFExit
mnuEdit
Test out your application: Press F5 and you should see your main MDI window appear with your menu system in place.
Copy Private Sub mnuFProducts_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles mnuFProducts.Click Dim frm As New frmProducts() frm.MdiParent = Me frm.Show() End Sub
This code declares a variable, frm, which refers to a new instance of the frmProducts form in the sample project. Then, you set the MdiParent property of the new form, indicating that its parent should be the current form (using the Me keyword). Finally, the code calls the Show method of the child form, making it appear on the screen. Some interesting things to note:
Me is a built-in keyword in Visual Basic .NETjust as in Visual Basic 6.0, this keyword refers to the class whose code is currently running. In this case, that's the MDI parent form, whose menu item you just clicked. You don't have to set the MdiParent property of the new child form. If you don't, the form will simply load as a new normal form, outside the MDI parent. As a matter of fact, you can set the MDI parent to be a different MDI container if you like. If you don't call the Show method, the child form won't ever display.
To uniquely identify each child form 1. Modify the mnuFProducts_Click procedure so that it looks like this:
Copy Private Sub mnuFProducts_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles mnuFProducts.Click Dim frm As frmProducts Static intCount As Integer frm = New frmProducts() ' Increment the caption counter. intCount += 1 ' Set the caption to be unique. frm.Text = frm.Text & " " & intCount.ToString() frm.MdiParent = Me frm.Show() End Sub
2. Run the project, create a few Products forms, and note that the caption of each form includes a different number. Note What's that Statickeyword? Using Static, rather than Dim, to declare a variable inside a procedure creates a variable that maintains its value from one invocation of the procedure to the next. When you declare a variable using Dim, that variable gets reinitialized each time the procedure is called. When you use Static, the variable maintains its value. That's what you want, in this caseyou want intCount to maintain its value, so that it continues to increment each time you create a new instance of frmProducts.
Value
Add MergeItems Remove Replace
Description
The MenuItem is added to the collection of existing MenuItem objects in a merged menu. (Default) All submenu items of this MenuItem are merged with those of existing MenuItem objects at the same position in a merged menu. The MenuItem is not included in a merged menu. The MenuItem replaces an existing MenuItem at the same position in a merged menu.
By default, a menu item's MergeOrder property is set to 0. The MergeType property is set to Add by default. This means that if you create a child form with a menu on it, the menu will be added at the end of the main menu. Consider Figure 3, which shows a child form called from the parent form's main menu. This form has a Maintenance menu on it (and the parent form does not). All of the items on the parent's main menu have their MergeOrder properties set to 0 and this menu's MergeOrder property is set to 0, so this menu will be added at the end of the main menu on the MDI parent form.
Figure 3. A child form that has menus will by default be added to the end of the main menu To create the form in Figure 3 1. 2. 3. 4. 5. On the Project menu, click Add Windows Form. Set the new form's name to frmChildWithMenus.vb. Add a MainMenu control to this form. Set the Name property for the MainMenu control to mnuMainMaint. Add the following menus as shown in Table 2. Table 2. Windows Form menus
Menu
&Maintenance &Suppliers &Categories
Name
mnuMaint mnuMSuppliers mnuMCategories
If you were to call this form exactly like you did the Products form in the previous section you will see that your main form looks like Figure 4. You can see that by default, the menu is added to the end of this form.
Figure 4. Menus are added to the end of the main menu by default Call this form by adding a new menu item under the File menu: 1. 2. 3. 4. 5. Open frmMain.vb in Design view. Click on the separator after the Products menu item and press the Insert key to add a new menu item. Type Child form with Menus as the text of this new menu item. Set the Name property of this new menu item to mnuFChild. Double click this new menu item and modify its Click event handler so that it looks like this:
Copy Private Sub mnuFChildMenus_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles mnuFChildMenus.Click Dim frm As New frmChildWithMenus() frm.MdiParent = Me frm.Show() End Sub
Note If you wish to merge the Maintenance menu in between the Edit and Window menus, you could set the MergeOrder property on the Edit menu item to 1, and the MergeOrder property on the Window menu to a 2. Then on the Maintenance menu item on frmChildWithMenus, set the MergeOrder property to 1 and leave the MergeType with its default value, Add. Taking these steps will add the Maintenance menu after the menu on the main form with the same MergeOrder number as it has (that is, after the Edit menu, but before the Window menu).
Menu Item
Tile Horizontal Tile Vertical Cascade Arrange Icons
Enumerated Value
MdlLayout.TileHorizontal MdiLayout.TileVertical MdiLayout.Cascade MdiLayout.ArrangeIcons
Add some menus to your main form for each of these options: 1. 2. 3. Open frmMain.vb in Design view. On the Window menu, double-click Cascade. For the Cascade menu item, modify the Click event handler so that it looks like the following:
Copy Private Sub mnuWCascade_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles mnuWCascade.Click Me.LayoutMdi(MdiLayout.Cascade) End Sub
On the Window menu, double-click each menu item and add the appropriate code. Tip The LayoutMDI method replaces the Arrange method you may have used in Visual Basic 6.0.
Copy Private Sub mnuWindow_Popup( _ ByVal sender As Object, _ ByVal e As System.EventArgs) _ Handles mnuWindow.Popup mnuWCenterChild.Enabled = _ Not (Me.ActiveMdiChild Is Nothing)
End Sub
4. 4.Run the project, and verify that if you have child windows displayed, the Center Child Form menu item is enabled. If there isn't a child form open, verify that the menu item is disabled.
The Popup event occurs when you select a menu item that includes sub-items. (You can't use the Click event, since that event doesn't occur for menu items that contain sub-items.) The Is operator allows you to compare values to the built-in value Nothing. In this case, the ActiveMdiChild property returns this special value if it doesn't refer to a form, and you must use the Is operator to check for this. (The = operator checks values for equality: the Is operator checks references to objects for equality.) The syntax of the procedure may be confusing. The value in parentheses ( Me, ActiveChild, Is, Nothing) returns a Boolean value: it's either True or False. The Not operator toggles the returned value to be the opposite Boolean value. The whole line of code assigns the return value from the expression in parentheses to the Enabled property of the menu item. In this case, if it's not true that the ActiveChild is Nothing, you'll enable the menu item. If it's True, you'll disable the menu item.
3. 4. 5. 6.
Double-click this control to add it to the tray area of the form. Click the ContextMenu control to give it focus. Change the Name property to cmnuProdID. Add the menu items (shown in Table 4) to this control, and set the Name properties as shown. When you add to a context menu, you start with the first menu item under the top-level menu. Figure 5 shows the finished context menu. Table 4. Context menu items
Menu
&Lookup &Copy &Paste
Name
mnuPLookUp mnuPCopy mnuPPaste
Figure 5. When adding items to the ContextMenu control, create a top-level item that won't ever be displayed as the parent for your items 7. 8. 9. Click the Product ID text box. In the Properties window, set the ContextMenu property to the ContextMenu control you just created, cmnuProdID. Run the project. On the File menu, click Products to create a child form, and righ-click on the Product ID text box to see the context menu appear.
If you were completing this form, you could now add code to respond to the Click events on each of these menus.
1. 2. 3.
Open frmMain.vb in Design view. Click the File menu to display its sub-items. Add three menu items, as described in Table 5. Table 5. File menu items
Menu
&Add Menus &Remove Menus &Add &New Menu
Name
mnuFAddMenus mnuFRemoveMenus mnuFAddNew
Copy Private Sub mnuFAddMenus_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles mnuFAddMenus.Click If Not mnuFAddMenus.Checked Then mnuFAddMenus.Checked = True End If End Sub
3. To repeat the previous two steps, on the File menu, double-click Remove Menus and modify its Click event procedure so that it looks like this:
Copy Private Sub mnuFRemoveMenus_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles mnuFRemoveMenus.Click If mnuFAddMenus.Checked Then mnuFAddMenus.Checked = False End If End Sub
4. Run the project, and on the File menu, double-click Add Menus. Verify that you see a check next to the item. To repeat, on the File menu, click Remove Menus to verify that the check has been removed.
Copy Private Sub mnuFAddMenus_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles mnuFAddMenus.Click If Not mnuFAddMenus.Checked Then mnuFAddMenus.Checked = True ' Adds these menus to the end of the File menu With mnuFile.MenuItems .Add("New Menu 1") .Add("New Menu 2") End With End If End Sub
Each menu item contained within the MainMenu (or ContextMenu) control is itself a MenuItem object, and just as with any other object, you refer to the menu items using the Name property you assigned to each. If a menu item contains other menu items (as each top-level menu item does), you can use its MenuItems property to refer to the collection of menu items it contains. In this case, you called the Add method of a MenuItem object (mnuFile) to add menu items to the collection of items. (In this example, mnuFile was the name you assigned to the File menu item.) Removing Menus Programmatically To remove menu items programmatically, you can either call the MenuItem collection's Remove or RemoveAt method. Remove requires you to provide a MenuItem object; if you instead want to remove items by their position within the menu, call the RemoveAt method. In this example, the simplest way to remove the menu items you created in the previous steps is to specify their position within the menu. You'll call the RemoveAt method to do the work. Because menu items are numbered starting at 0 (as are all collections and arrays in Visual Basic .NET), you need to take that into account when removing menu items.
To handle removing the two menu items you've just added, modify the Click event procedure for the Remove Menus items on the File menu, so that the procedure looks like this:
Copy Private Sub mnuFRemoveMenus_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles mnuFRemoveMenus.Click If mnuFAddMenus.Checked Then With mnuFile.MenuItems ' Remove the last two items .RemoveAt(.Count - 1) .RemoveAt(.Count - 1) End With mnuFAddMenus.Checked = False End If End Sub
Run the project to verify that choosing the Add and Remove Menus menu items correctly adds and removes the two extra items.
Copy Private Sub RadioCheck_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles mnuWArrange.Click, mnuWCascade.Click, _ mnuWHorizontal.Click, mnuWVertical.Click
mnuWArrange.Checked = False mnuWCascade.Checked = False mnuWHorizontal.Checked = False mnuWVertical.Checked = False CType(sender, MenuItem).Checked = True End Sub
6. Run the project, create some Product forms, and use the Window menu items to arrange the children. As you use the Cascade, Tile Horizontal, and other menu items, you should see a circle next to the most recently selected item. Figure 6 shows the results of adding this new feature.
Figure 6. Setting a menu item's RadioCheck property to True shows a dot, rather than a check, next to selected items
The procedure you want to call must match the procedure signature of the standard Click event for menu items. That is, it must receive two parameters (one as System.Object, the other as System.EventArgs) and return nothing at all. (It must be a Sub, in other words.)
You must add a Handles clause for each event you want to handle. In this case, you're handling the Click event of four different menu items. Within the procedure, you can use the first parameter (named sender, in this example) to figure out which object triggered the event. This example first sets each of the four items to be unchecked, and then checks the item that triggered the event.
It's also interesting to note how the RadioCheck_Click procedure set the RadioCheck property of the object it received as its first parameter. To convert the Object variable into a MenuItem type, the code calls the CType function, indicating the variable to convert, and the result type (MenuItem):