Wednesday, 31 August 2011

Add a Menu to Another Program


This code shows you how to add a menu to another program. The only thing is that nothing will happen when you click on the items. To make something happen when you click on an item you have to subclass the menu (I'd help with that but I don't have any subclassing controls, or at least not right now). Put this in your *.bas file:

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
Public Declare Function CreatePopupMenu Lib "user32" () As Long
Public Declare Function DrawMenuBar Lib "user32" (ByVal hwnd As Long) As Long
Public Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long
Public Declare Function GetMenu Lib "user32" (ByVal hwnd As Long) As Long
Public Declare Function GetMenuItemID Lib "user32" (ByVal hMenu As Long, ByVal nPos As Long) As Long
Public Declare Function GetMenuItemCount Lib "user32" (ByVal hMenu As Long) As Long
Public Declare Function GetMenuString Lib "user32" Alias "GetMenuStringA" (ByVal hMenu As Long, ByVal wIDItem As Long, ByVal lpString As String, ByVal nMaxCount As Long, ByVal wFlag As Long) As Long
Public Declare Function GetSubMenu Lib "user32" (ByVal hMenu As Long, ByVal nPos As Long) As Long
Public Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long

Public Const MF_ENABLED = &H0&
Public Const MF_POPUP = &H10&
Public Const MF_STRING = &H0&
Public Const WM_NCPAINT = &H85
Then put something like this in a button:
Dim newMenu As Long
newMenu = CreatePopupMenu
Call AppendMenu(newMenu, MF_ENABLED Or MF_STRING, 0, "Item One")
Call AppendMenu(newMenu, MF_ENABLED Or MF_STRING, 1, "Item Two")
Call AppendMenu(newMenu, MF_ENABLED Or MF_STRING, 2, "Item Three")
Call AppendMenu(newMenu, MF_ENABLED Or MF_STRING, 3, "Item Four")
Call AppendMenu(newMenu, MF_ENABLED Or MF_STRING, 4, "Item Five")

' Find the notepad application window
Dim notepad As Long
notepad = FindWindow("notepad", vbNullString)

' Add our menu to the window we found above
Dim notepadMenu As Long
notepadMenu = GetMenu(notepad)
Call AppendMenu(notepadMenu, MF_POPUP, newMenu, "Item List")

' Ensure that the user sees the new menu immediately
Call SendMessage(notepad, WM_NCPAINT, 0&, 0&)

No comments:

Post a Comment

Blogger Widgets Twitter Bird Gadget