【问题标题】:Overriding ComboBox to select item by pressing index through keyboard in C#在 C# 中通过键盘按索引覆盖 ComboBox 以选择项目
【发布时间】:2011-08-05 11:19:18
【问题描述】:

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

示例:

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

'J'被按下时Jan被选中,'F'代表'Feb', ....

我想这样用,当

1 被按下,然后 Jan
2Feb 等等。

有可能吗?如果是,我该如何实现?

【问题讨论】:

  • ComboBox 上没有 KeyDown/KeyUp 事件吗?

标签: c# .net winforms combobox


【解决方案1】:

这仅在组合设置为 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);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-21
    • 2011-01-13
    • 2021-04-09
    相关资源
    最近更新 更多