VB Center | Code Library | Menus

Adding Radio Buttons to a Menu, Replacing the Default Checkmarks

Written exclusively for VB Center by Marco Cordero. Portions of this code sample were written by Randy Birch.


Start a new project. To the form, add the following menus.

Type Name Index Caption
       
Menu Options   Options
Sub-Menu mnuOptions 0 Option Radio Item 1
Sub-Menu mnuOptions 1 Option Radio Item 2
Sub-Menu mnuOptions 2 Option Radio Item 3
Sub-Menu mnuOptions 3 -
Sub-Menu mnuOptions 4 Option Check Item 1
Sub-Menu mnuOptions 5 Option Check Item 2
Sub-Menu mnuOptions 6 Option Check Item 3

Add a module to your project. Place the following into the general declarations area of the module.

Public Const MIIM_STATE = &H1
Public Const MIIM_ID = &H2
Public Const MIIM_SUBMENU = &H4
Public Const MIIM_CHECKMARKS = &H8
Public Const MIIM_TYPE = &H10
Public Const MIIM_DATA = &H20
Public Const MFT_RADIOCHECK = &H200&

Public Type MENUITEMINFO
cbSize As Long
fMask As Long
fType As Long
fState As Long
wID As Long
hSubMenu As Long
hbmpChecked As Long
hbmpUnchecked As Long
dwItemData As Long
dwTypeData As String
cch As Long
End Type

Public Declare Function SetMenuItemInfo Lib "user32" _
Alias "SetMenuItemInfoA" _
(ByVal hMenu As Long, ByVal uItem As Long, _
ByVal fByPosition As Long, lpmii As MENUITEMINFO) As Long

Public Declare Function GetMenu Lib "user32" _
(ByVal hwnd As Long) As Long

Public Declare Function GetSubMenu Lib "user32" _
(ByVal hMenu As Long, _
ByVal nPos As Long) As Long


Add the following code to the form.

Private Sub SetRadioMenuChecks(Mnu As Menu, ByVal mnuItem&)

Dim hMenu&
Dim mInfo As MENUITEMINFO

' get the menu item handle
hMenu& = GetSubMenu(GetMenu(Mnu.Parent.hwnd), 0)

' copy it's attributes to the new Type,
' changing the checkmark to a radio button

mInfo.cbSize = Len(mInfo)
mInfo.fType = MFT_RADIOCHECK
mInfo.fMask = MIIM_TYPE
mInfo.dwTypeData = Mnu.Caption & Chr$(0)

' change the menu checkmark
SetMenuItemInfo hMenu&, mnuItem&, 1, mInfo

End Sub

 

Private Sub Form_Load()

' just change the radio check for the first 3 menu items
SetRadioMenuChecks mnuOptions(0), 0
SetRadioMenuChecks mnuOptions(1), 1
SetRadioMenuChecks mnuOptions(2), 2

End Sub

 

Private Sub mnuOptions_Click(Index As Integer)

Static prevSelection As Integer

mnuOptions(prevSelection).Checked = False
mnuOptions(Index).Checked = True
prevSelection = Index

End Sub


Now, press F5 to run the project. If you click one of the menu items labeled "Menu Radio Item", you will see a radio button appear beside the menu item. If you click one of the menu items labeled "Menu Check Item", you will see a checkmark appear beside the menu item.

Back to Code Library - Menus

1