click a context menu item using sendmessage (or si

2019-08-13 22:53发布

问题:

I need to right click on another application, gets it context menu (that was opened after the right click), and than select an item from it.

I can use the postMessage with the other application handle, and as a results the requested context menu did appear, but I have no idea of how to select from it.

    public  const int WM_RBUTTONDOWN = 0x0204;

    public  const int WM_RBUTTONUP = 0x0205;


    [System.Runtime.InteropServices.DllImport("user32.dll", EntryPoint = "SendMessage", CharSet = System.Runtime.InteropServices.CharSet.Auto)]

    public static extern void SendMessage(IntPtr hWnd, int msg, int wParam, int lParam);



    [System.Runtime.InteropServices.DllImport("user32.dll", EntryPoint = "PostMessage", CharSet = System.Runtime.InteropServices.CharSet.Auto)]

    public static extern void PostMessage(IntPtr hWnd, int msg, int wParam, int lParam);



    Point p = Cursor.Position;

    PostMessage((IntPtr)123456, WM_RBUTTONDOWN, 0, 0);

    PostMessage((IntPtr)123456, WM_RBUTTONUP, 0, 0);

what should I do next (now the context menu is open)?

thanks, Tomer.

回答1:

I guess you want to trigger a specific action. No need to popup the context menu: Just post a WM_COMMAND message that matches the context menu item you want to select. You'll find the WM_COMMAND item id associated to the desired menu item using tools such as Spy++ or Winspector.

PostMessage((IntPtr)hWnd, WM_COMMAND, 0, ID_MENU_ITEM);

EDIT: Clarification in answer to your comment:

You send or post the WM_COMMAND message straight to the main window, not to the menu. Actually, you don't need to popup the menu at all. The context menu is just a GUI element that lets the user select an action. The application doesn't need the menu to show up in order to convey said action.