windows 以编程方式关闭 MenuStrip
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2894894/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Closing a MenuStrip programmatically
提问by Nilbert
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.
我有一个已添加到表单的 MenuStrip,在其中的一个下拉菜单中,我有一个文本框。当我在文本框上按 Enter 键时,我希望运行一个函数,然后关闭下拉菜单。我知道如何完成输入部分,但我不知道如何关闭 MenuStrip 下拉菜单。
回答by Hans Passant
Call the Owner's Hide() method. For example:
调用所有者的 Hide() 方法。例如:
private void toolStripTextBox1_KeyDown(object sender, KeyEventArgs e) {
if (e.KeyData == Keys.Enter) {
e.SuppressKeyPress = true;
toolStripTextBox1.Owner.Hide();
}
}
回答by WereWolf
You can try this (worked for me)
你可以试试这个(对我有用)
for(int x = 0; x < menu.Items.Count; x++)
((System.Windows.Forms.ToolStripDropDownItem)menu.Items[x]).HideDropDown();
for(int x = 0; x < menu.Items.Count; x++)
((System.Windows.Forms.ToolStripDropDownItem)menu.Items[x]).HideDropDown();
回答by JuanR
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.
HideDropDown()
无论您的文本框(或其他控件)是如何嵌套的,您都需要调用主菜单项的方法。
For instance, let's say you have a tool strip with File
, Edit
, Help
. On the Edit
menu, you have your textbox nested somewhere:
例如,假设您有一个带有File
, Edit
,的工具条Help
。在Edit
菜单上,您的文本框嵌套在某处:
EditMenuItem -> FindMenuItem -> SearchTextBoxHere
EditMenuItem -> FindMenuItem -> SearchTextBoxHere
You would call the Edit menu's HideDropDown()
method on your textbox's keydown event:
您将HideDropDown()
在文本框的 keydown 事件上调用 Edit 菜单的方法:
EditMenuItem.HideDropDown();