简体   繁体   English

通过在C#中通过键盘按下索引来覆盖ComboBox以选择项目

[英]Overriding ComboBox to select item by pressing index through keyboard in C#

I want to override a combobox such that it can be selected by its position in the list by pressing key through keyboard. 我想覆盖一个组合框,以便通过按键盘上的键可以通过其在列表中的位置进行选择。

Example: 例:

ComboBoxMonths
  - Jan
  - Feb
  - Mar
  - Apr
  - May
  - Jun
  . . .

When 'J' is pressed Jan is selected, and 'F' for 'Feb' ,.... “J”被压被选择,和“F”“月”,....

I want to use it like this, when 我想这样使用它

1 is pressed then Jan , 1然后1月
2 for Feb , etc. 2表示2月依此类推

Is it possible ? 可能吗 ? If yes, How can I achieve that ? 如果是,我该如何实现?

This only works properly if the combo is set to DropDownList, which makes sense in your example. 仅当组合设置为DropDownList时,此方法才能正常工作,这在您的示例中很有意义。 It also only covers 1-9. 它也只涵盖1-9。 If you want to handle more than one digit, it requires more logic with timers. 如果要处理一个以上的数字,则需要使用计时器的更多逻辑。

public class MyComboBox : ComboBox
{
    protected override void OnKeyPress(KeyPressEventArgs e)
    {
        var index = e.KeyChar - '1';
        if( index >= 0 && index < this.Items.Count )
            this.SelectedIndex = index;

        base.OnKeyPress(e);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM