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

时间:2011-04-14 11:25:52

标签: c# .net winforms combobox

我想覆盖一个组合框,这样可以通过键盘上的按键来选择它在列表中的位置。

示例:

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

'J'被按下 Jan 时,'F' 'Feb', ....

我希望像

那样使用它 按

1 然后 Jan
2 2

有可能吗?如果是,我怎样才能实现这一目标?

1 个答案:

答案 0 :(得分:0)

只有在将组合设置为DropDownList时才能正常工作,这在您的示例中是有意义的。它也只涵盖1-9。如果要处理多个数字,则需要更多带定时器的逻辑。

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);
    }
}