如何按回车键选择列表框项?

时间:2014-08-19 05:57:16

标签: c# winforms visual-studio-2010

IDE:Visual Studio 2010,c#.net 4.0,winforms appication:

在我的应用程序中,我正在显示列表框。现在,当用户从键盘按下回车键时,我想在列表框中选择一个默认项目[列表框选择索引已更改事件将被调用]。

1 个答案:

答案 0 :(得分:0)

取决于Enter需要捕获的位置:

我接受了KeyUp事件,这里的有效事件是KeyPress,KeyDown和KeyUp事件

public class YourFormOrControllerName : Form //Or UserControl
{
    private int yourDefaultValue = 0;
    public YourFormOrControllerName()
    {
        //whenever you haven't selected a specific control to setup (not a so good solution)
        //YourFormOrControllerName.KeyUp += HandleKeyUpSelected;

        //Whenever you Enter in the ListBox
        YourListBoxControlName.KeyUp += HandleKeyUpSelected;
    }

    private void HandleKeyUpSelected(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
        {
            YourListBoxControlName.SelectedIndex = yourDefaultValue;
        }
    }
}

正如@Nyerguds在下面评论的那样,不同事件有不同的论点。有关更多信息,请参阅MSDN