What's New
Q & A
Tip Jar
C# Helper...
Follow VBHelper on Twitter
MSDN Visual Basic Community
TitleAdd (non-working) menu items to another application
Keywordsmenu, other program
CategoriesControls, Software Engineering
Use FindWindow to get the target's window handle. Use GetMenu, CreatePopupMenu, ModifyMenu, GetSubMenu, and AppendMenu. Finally use SetWindowLong to create a new WindowProc.

Unfortunately not all of this works. Even though AppendMenu returns a non-zero value to indicate success, it fails to create new system menu entries, and SetWindowLong fails so you cannot respond to the new menus.

If anyone figures out how to make the menus work, please let me know.

Private Sub CreateMenus()
Dim target_hwnd As Long
Dim form_menu As Long
Dim submenu2 As Long
Dim submenu2_list As Long
Dim i As Integer
Dim system_menu As Long
Dim menu_item As Long

    ' Get the handle to the Menu on the
    ' current form
    target_hwnd = FindWindow(vbNullString, Text1.Text)
    If target_hwnd = 0 Then
        MsgBox "Error finding target application"
        Exit Sub
    End If

    form_menu = GetMenu(target_hwnd)
    If form_menu = 0 Then
        MsgBox "Error getting main menu"
        Exit Sub
    End If
    ' Create a new popup menu to be used to
    ' place the required menu items.
    submenu2_list = CreatePopupMenu()
    If submenu2_list = 0 Then
        MsgBox "Error creating new menu"
        Exit Sub
    End If

    ' Modify the second menu option on the Form
    ' Menu (denoted by the position 1 -
    ' menu positions start with 0 for the first
    ' item, so 1 specifies the second item).
    ' Specify that the Submenu option will
    ' activate the new popup menu just created
    ' (given the new popup menu handle). Note:
    ' The last string parameter in the function
    ' call specifies the new menu option caption
    ' so if it is to stay the same, make this
    ' string the same as the original caption
    ModifyMenu form_menu, 0, MF_BYPOSITION + MF_POPUP, _
        submenu2_list, "New Menu Item"

    ' Get the handle of the second menu
    ' option on the Form Menu (denoted by the
    ' position 1)
    submenu2 = GetSubMenu(form_menu, 0)

    ' Add new items to the second menu option
    ' list ("Document List")
    For i = 1 To 5
        menu_item = AppendMenu(submenu2, MF_STRING + _
            MF_ENABLED, 1000 + i, "Document " & CStr(i))
    Next i

    ' Add "About" to the system menu.
    system_menu = GetSystemMenu(hwnd, False)
    AppendMenu system_menu, MF_SEPARATOR, 0, ""
    AppendMenu system_menu, MF_STRING + MF_ENABLED, _
        IDM_ABOUT, "About..."

    ' Replace the default WindowProc.
    OldWindowProc = SetWindowLong( _
        target_hwnd, GWL_WNDPROC, _
        AddressOf NewWindowProc)
End Sub
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.