当一个菜单下子菜单项较多时,一打开菜单就出现了长长的菜单项,如果其他的菜单项下子菜单较少,就显得很不协调。现在的一些软件还允许用户在已有的菜单中添加菜单项,这都会造成子菜单项过多的情况,如果能像某些软件那样将较多的子菜单项分成两列显示就显得美观多了。在VB中要实现这一功能还是比较方便的,下面举例说明。
实现菜单分割这一功能需要使用API函数,思路是:首先获得菜单句柄,从而可得到其子菜单项数,然后将子菜单项数除以2,若子菜单项数为奇数,则将多余的一项划到第一部分,然后利用API函数SetMenuItemInfo重新设定菜单显示形式即可。
下面是一个例子。首先用菜单生成器制做一个包括9个子菜单项的菜单,然后,在总体声明部分声明用到的API函数和常数,这些可以从API说明文件中复制。
Option Explicit
′菜单信息结构说明
Private 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
′所需的API函数和常数
Private Declare Function GetMenu Lib ″user32″ -
(ByVal hwnd As Long) As Long
Private Declare Function GetMenuItemCount Lib″user32″ -
(ByVal hMenu As Long) As Long
Private Declare Function GetSubMenu Lib ″user32″ -
(ByVal hMenu As Long, ByVal nPos As Long) As Long
Private Declare Function GetMenuItemInfo Lib ″user32″ -
Alias ″GetMenuItemInfoA″(ByVal hMenu As Long, ByVal un As Long, -
ByVal b As Boolean, lpmii As MENUITEMINFO) As Long
Private Declare Function SetMenuItemInfo Lib ″user32″ -
Alias ″SetMenuItemInfoA″(ByVal hMenu As Long, ByVal uItem As Long, -
ByVal fByPosition As Long, lpmii As MENUITEMINFO) As Long
Const MIIM—TYPE=&H10
Const RGB—STARTNEWCOLUMNWITHVERTBAR=&H20&
Const MFT—STRING=&H0&
在窗体中添加一个命令按钮,Caption=“分割菜单”,双击写如下代码:
Private Sub Command1—Click()
Dim rv As Long
Dim hSubMenu As Long
Dim mnuItemCount As Long
Dim mInfo As MENUITEMINFO
Dim pad As Long
′获取菜单项句柄和子菜单项数
hSubMenu=GetSubMenu(GetMenu(Me.hwnd), 0)
mnuItemCount=GetMenuItemCount(hSubMenu)
′将子菜单项分成两部分
If mnuItemCount Mod 2<>0 Then pad=1
′取得当前菜单信息
mInfo.cbSize=Len(mInfo)
mInfo.fMask=MIIM—TYPE
mInfo.fType=MFT—STRING
mInfo.dwTypeData=Space$(256)
mInfo.cch=Len(mInfo.dwTypeData)
rv=GetMenuItemInfo(hSubMenu, (mnuItemCount/2)+pad, True, mInfo)
′按新格式显示菜单
mInfo.fType=RGB—STARTNEWCOLUMNWITHVERTBAR
mInfo.fMask=MIIM—TYPE
rv=SetMenuItemInfo(hSubMenu, (mnuItemCount/2)+pad, True, mInfo)
If rv Then MsgBox ″ 分割完毕″
End Sub
运行后按命令按钮,将发现子菜单项分成了两部分,左边五项,右边四项。  
|