How to determine a menu item's ID (for PostMessage) in a WinForms context RRS feed

  • Question

  • Hi.  I am trying to send a menu click from one window to another in my WinForms application.  I believe that PostMessage will to the trick for me, if I can determine the menu ID number I am targeting.  I've experimented with Spy++, but it seems the ID can change with every build.  I see no obvious way to define it myself in code.

    I gave the GetMenuItemID function (user32) a try, but it returns -1.  The window has File and Edit for menus, and New and Open below File. For the menu handle, I passed targetwindowinstance.FileMenuItem.DropDown.Handle.  I passed an index of 1, looking for the Open menu item.

    I'm using C# in VS2010.  Any ideas more than welcome.

    Arthur Gardner
    Friday, February 3, 2012 7:46 PM

All replies

  • Hi Arthur,
    Instead of using Win32 API calls and platform invoking, you can simply expose a method in one of the forms that will do it for you.


    public class Form1 : Form {
        public void ClickMenuItem() {
    public class Form2 : Form {
        // Initialize this instance of Form1 from somewhere
        private Form1 m_Form1;
        public void ImCalledFromSomewhereInCode() {


    Currently developing FaultTrack. I occassionally blog about C# and .NET.
    Hoping to become a MVP by 2013. Email: danderson [at] dcomproductions [dot] com
    Saturday, February 4, 2012 1:08 AM
  • Thanks, Dave.

    That's what my program currently does.  Here's the problem I have with it.  Form1 (the target) is an MDI parent form.  The command is specifically to open a new child form.  If there is already a child form on Form1, then the MDI logic becomes confused.  The new child has no minimize/restore/close buttons when maximized, and the wrong child is checked in the parent form's Windows menu.

    So I just guessed that the confusion might arise from the fact that this open request is called from another window's loop.  The calling window is not a child form, but an independent window in the same application.

    I believe I got one brief verification of my theory, by making the PostMessage call using a hard-wired menu ID.  But I don't know how to make that solution stick.

    I would be thrilled to use nothing but bona fide .NET API's, but there always seem to be these little holes.

    Arthur Gardner
    Monday, February 6, 2012 2:40 PM