May 8, 1995
Within a Visual Basic® application, you can execute a menu item in another Windows®-based program. This article explains how to use several Windows application programming interface (API) functions to execute menu commands.
In some situations, you may need to actuate an application, such as Notepad, and execute one or more of that application's menu commands. The Windows® application programming interface (API) provides several functions that enable you to perform this type of operation in Visual Basic®.
The following example program executes another application's menu commands. This program assumes that the Windows Notepad application program is already running in memory. This program uses SendMessage to execute the File/Open menu selection in Notepad.
When you execute the program, click the Command Button. After a second or two, you will see that Notepad has been activated and that its Open File dialog box is displayed on the screen.
Private Declare Function FindWindow Lib "User" (ByVal lpClassName As Any, ByVal
lpWindowName As Any) As Integer
Private Declare Function GetMenu Lib "User" (ByVal hWnd As Integer) As Integer
Private Declare Function GetMenuItemID Lib "User" (ByVal hMenu As Integer, ByVal
nPos As Integer) As Integer
Private Declare Function GetSubMenu Lib "User" (ByVal hMenu As Integer, ByVal
nPos As Integer) As Integer
Private Declare Function SendMessage Lib "User" (ByVal hWnd As Integer, ByVal
wMsg As Integer, ByVal wParam As Integer, lParam As Any) As Long
Const WM_COMMAND = &H111
Private Sub Command1_Click()
Dim hWnd As Integer
Dim hMainMenu As Integer
Dim hMenu As Integer
Dim MenuID As Integer
hWnd = FindWindow("NotePad", "Untitled - NotePad")
If hWnd = 0 Then Exit Sub
hMainMenu = GetMenu(hWnd)
hMenu = GetSubMenu(hMainMenu, 0)
MenuID = GetMenuItemID(hMenu, 1)
AppActivate "Untitled - NotePad"
X& = SendMessage(hWnd, WM_COMMAND, MenuID, 0&)
End Sub
Knowledge Base Q71281. "How to Implement a Bitmap Within a Visual Basic Menu." (MSDN Library, Knowledge Base)
Knowledge Base Q113475. "How to Get a Window Handle Without Specifying an Exact Title." (MSDN Library, Knowledge Base)
"Adding Pop-Up Menus to Your Programs." (MSDN Library, Periodicals)