4

I have a MenuStrip that I have added to a form, and in one of the dropdown menus in it, I have a text box. When I hit enter on the textbox, I want a function to run, then the drop down menu to close. I know how to get the enter part done, but I have no idea how to close the MenuStrip dropdown menu.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Nilbert
  • 1,112
  • 3
  • 14
  • 26

3 Answers3

10

Call the Owner's Hide() method. For example:

    private void toolStripTextBox1_KeyDown(object sender, KeyEventArgs e) {
        if (e.KeyData == Keys.Enter) {
            e.SuppressKeyPress = true;
            toolStripTextBox1.Owner.Hide();
        }
    }
Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
  • What if it's a submenu of another menu? How do I go up the chain of submenus to get to the very root of the menu? I tried Owner.Owner but that's undefined and Owner.Parent results in an Exception of "Parent not set". – Nilbert May 25 '10 at 16:21
  • Just call the HideDropDown() method of the particular menu item you want to hide. – Hans Passant May 25 '10 at 16:54
3

You can try this (worked for me)

for(int x = 0; x < menu.Items.Count; x++) ((System.Windows.Forms.ToolStripDropDownItem)menu.Items[x]).HideDropDown();

amesh
  • 1,311
  • 3
  • 21
  • 51
WereWolf
  • 31
  • 1
1

This is an old question, but I ran into the same issue and figured out the solution, so for others out there:

You need to call the HideDropDown() method of the main menu item, regardless of how nested your textbox (or other control) is.

For instance, let's say you have a tool strip with File, Edit, Help. On the Edit menu, you have your textbox nested somewhere:

EditMenuItem -> FindMenuItem -> SearchTextBoxHere

You would call the Edit menu's HideDropDown() method on your textbox's keydown event:

EditMenuItem.HideDropDown();
JuanR
  • 7,405
  • 1
  • 19
  • 30