如何强制 DropDownList 样式的 ComboBox 仅在用户单击下拉按钮时打开?
在 C# .NET 2.0 中,我有一个带有 ComboBoxStyle DropDownList 的 WinForms ComboBox。 但是,只要用户单击组合框上的任意位置,就会出现下拉菜单。 相反,我希望仅当用户明确单击下拉按钮时才打开它。 当用户单击组合框的其余部分时,我想为其分配键盘焦点,以便他或她可以在所选项目上使用一些键盘命令。 最好的方法是什么?
In C# .NET 2.0, I have a WinForms ComboBox with ComboBoxStyle DropDownList. However, the drop down appears whenever the user clicks anywhere on the combo box. Instead, I'd like to have it only open when the user explicitly clicks on the drop down button. When the user clicks on the rest of the combo box, I'd like to just assign it the keyboard focus so he or she can use some keyboard commands on the selected item. What's the best way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在其他答案的帮助下,我得出了这个快速解决方案:
After some help from the other answers, I arrived at this quick solution:
你有两个问题需要考虑。 第一个相当简单:确定是否应打开或关闭下拉菜单。 这段代码可以做到这一点:
第二个问题更重要——实际上阻止了下拉菜单的出现。 最简单的方法是:
但是,这允许在框中输入内容,而您可能不希望这样做。
我花了大约 15 分钟查看选项,看来为了防止出现下拉列表并同时防止用户在下拉列表中键入内容,您需要对控件进行子类化。 这样,您可以重写 OnMouseClick(),并且仅在单击按钮时调用 base.OnMouseClick() 。 它看起来像这样(未经测试):
You have two issues to consider. The first is rather simple: determine whether the dropdown should be opened or closed. This code can do that:
The second issue is more significant -- actually preventing the dropdown from appearing. The simplest approach is:
But, that allows typing into the box, which you may not want.
I spent about 15 minutes looking at options, and it appears that to prevent the dropdown from appearing and simultaneously prevent the user from typing into the dropdown, you would need to subclass the control. That way, you can override OnMouseClick(), and only call the base.OnMouseClick() when they did click on button. It would look something like this (untested):
您也许可以获得鼠标单击的 X、Y 位置,如果它不在下拉“图标”上(因为缺乏更好的词),您可以从那里强制它折叠。
You may be able to get the X,Y position of the mouse click, and from there you could force it collapsed if it isn't on the drop down "icon" (for lack of a better word).