PDA

Click to See Complete Forum and Search --> : Sending menu command


WadeD
Jan 5th, 2000, 01:08 AM
Hi, how can I select the menu commands of another application that's open without showing the user? SendKeys is visible to the user.

Could I use sendmessage api? The examples that I have seen have been for pressing a button or clicking the title bar.

Thanks so much,
Wade

Aaron Young
Jan 5th, 2000, 03:36 AM
You can use the Menu API's to Locate the Menu then Find the Item you want to Run, once you have it, you can get the Item ID and use this with the SendMessage API to Execute it, without it looking as though anything was selected, ie.

Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long
Private Declare Function GetMenu Lib "user32" (ByVal hwnd As Long) As Long
Private Declare Function GetSubMenu Lib "user32" (ByVal hMenu As Long, ByVal nPos As Long) As Long
Private Declare Function GetMenuItemCount Lib "user32" (ByVal hMenu As Long) As Long
Private Declare Function GetMenuItemID Lib "user32" (ByVal hMenu As Long, ByVal nPos As Long) As Long
Private 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

Private Const WM_COMMAND = &H111
Private Const MF_BYPOSITION = &H400&

Private Function RunMenuItem(ByVal sMenu As String, sItem As String, ByVal lhWnd As Long) As Boolean
Dim lMenu As Long
Dim lMenuCount As Long
Dim iItem As Integer
Dim sCaption As String * 255

'Find the Specified Menu..
lMenu = GetMenu(lhWnd)
lMenuCount = GetMenuItemCount(lMenu)
For iItem = 1 To lMenuCount
Call GetMenuString(lMenu, iItem - 1, ByVal sCaption, 255, MF_BYPOSITION)
If Replace(LCase(Left$(sCaption, InStr(sCaption, Chr(0)) - 1)), "&", "") = LCase(sMenu) Then
Exit For
End If
Next
If iItem > lMenuCount Then Exit Function 'Menu not Found

'Find the Specified Item..
lMenu = GetSubMenu(lMenu, iItem - 1)
lMenuCount = GetMenuItemCount(lMenu)
For iItem = 1 To lMenuCount
Call GetMenuString(lMenu, iItem - 1, ByVal sCaption, 255, MF_BYPOSITION)
If Replace(LCase(Left$(sCaption, InStr(sCaption, Chr(0)) - 1)), "&", "") = LCase(sItem) Then
'Get the Item ID
lMenu = GetMenuItemID(lMenu, iItem - 1)
'Call the Menu Item, (Execute it).
Call SendMessage(lhWnd, WM_COMMAND, lMenu, ByVal 0&)
RunMenuItem = True
Exit Function
End If
Next
End Function

Usage: RunMenuItem({Menu Name}, {Item Name}, {Window Handle}) - Returns True/False

Example:

If RunMenuItem("file", "exit", lAppHwnd) = False Then Msgbox "Unable to Locate Menu Item"

Where lAppHwnd is the Window Handle of the Form/Window containing the Menu you want to run the Item from.

------------------
Aaron Young
Analyst Programmer
aarony@redwingsoftware.com
ajyoung@pressenter.com