添加自定义菜单项到窗体的控制菜单 刘红军 2000年 第37期   有些小软件为了使界面更简洁,干脆把自定义菜单项添加到窗体的控制菜单中。由于控制菜单是由Windows系统直接控制的,因此,在控制菜单上添加自定义菜单项,必须借助API函数来实现。笔者经反复调试,在VB中实现了这一功能。具体实现分以下两步完成:   第一,把自定义菜单项添加到控制菜单中。   第二,给菜单项添加相应的代码。基本原理:当我们单击控制菜单中某一项时,窗体会收到一条WM_SYSCOMMAND消息(在wMsg中),该消息包含了控制菜单中被单击那一项的标识符ID(在wParam中)。此时,窗体的默认函数会根据WM_SYSCOMMAND消息以及菜单标识符ID执行相应的操作,完成菜单命令。我们拦截到达窗体的WM_SYSCOMMAND消息,并且识别出菜单的标识符ID,使自己的菜单项执行指定的动作。 下面的例子用于在控制菜单上添加一条分隔符和两条菜单项。   新建工程,添加新模块,在模块中声明:   ′菜单API函数声明   Public Declare Function GetSystemMenu Lib ″user32″ (ByVal hwnd As Long,ByVal bRevert As Long) As Long   Public Declare Function AppendMenu Lib ″user32″ Alias ″AppendMenuA″ (ByVal hMenu As Long,ByVal wFlags As Long,ByVal wIDNewItem As Long,ByVal lpNewItem As Any) As Long   ′窗口API函数声明   Public Declare Function SetWindowLong Lib ″user32″ Alias ″SetWindowLongA″ (ByVal hwnd As Long,ByVal nIndex As Long,ByVal dwNewLong As Long) As Long   Public Declare Function CallWindowProc Lib ″user32″ Alias ″CallWindowProcA″ (ByVal lpPrevWndFunc As Long,ByVal hwnd As Long,ByVal Msg As Long,ByVal wParam As Long,ByVal lParam As Long) As Long   ′消息   Public Const GWL_WNDPROC = (-4)   Public Const WM_SYSCOMMAND = &H112   ′自定义菜单项的ID   Public Const MENU_ABOUT = 1   Public Const MENU_HELP = 2   ′其他变量   Public PrevWndFunc As Long   Public Function MenuFunc(ByVal hwnd As Long,ByVal wMsg As Long,ByVal wParam As Long,ByVal lParam As Long) As Long   ′wMsg:被发送的消息    If wMsg = WM_SYSCOMMAND Then    ′进一步检查是否是自定义菜单项的ID    Select Case wParam    ′″关于...″菜单项    Case MENU_ABOUT    ′此处可加入″关于…″菜单项的代码    MsgBox ″Success for you!″,vbInformation,″关于...″    ′″帮助″菜单项    Case MENU_HELP    MsgBox ″Hi,How are you?″,vbInformation,″帮助″    ′其它菜单项交给系统处理    Case Else    MenuFunc = CallWindowProc(PrevWndFunc,hwnd,wMsg,wParam,lParam)    End Select    Else    MenuFunc = CallWindowProc(PrevWndFunc,hwnd,wMsg,wParam,lParam)    End If   End Function   ′窗体中的代码:   Private Sub Form_Load()   ′取得指定窗体控制菜单的句柄。   Dim hMenu As Long   hMenu = GetSystemMenu(Me.hwnd,False)   ′在控制菜单中添加自定义的2条菜单项    ′添加分隔符   AppendMenu hMenu,0,0,vbNullString   ′添加″关于…″菜单项   AppendMenu hMenu,0,MENU_ABOUT,″关于...″   ′添加″帮助″菜单项   AppendMenu hMenu,0,MENU_HELP,″帮助″   ′加载自定义窗口函数   PrevWndFunc = SetWindowLong(Me.hwnd,GWL_WNDPROC,AddressOf MenuFunc)   End Sub   Private Sub Form_Unload(Cancel As Integer)   Unload Me   End Sub   说明:该程序在Win98、VB6.0中运行通过。