当文本框具有焦点而不移动光标时,使用向上/向下键滚动列表框

Bro*_*ymb 3 c# textbox listbox winforms

我有一个TextBox用户可以输入搜索词并ListBox显示结果的。还有一个按钮将根据单击时选择的项目显示一些信息。

我正在尝试使用向上和向下箭头键在列表框中滚动,以便用户不必单击项目,然后单击按钮。那时,我最好还是依靠双击事件来完成工作,因为它们已经在项目上了。但是,我正在尝试使其更加“仅键盘友好”。
以下代码有效,但有一个小缺陷:

private void txtSearchTerm_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Down && Results.SelectedIndex < (Results.Items.Count - 1))
    {
        Results.SelectedIndex++;
    }
    else if (e.KeyCode == Keys.Up && Results.SelectedIndex > 0)
    {
        Results.SelectedIndex--;
    }
}  
Run Code Online (Sandbox Code Playgroud)

使用此代码,光标将随所选项目的更改而左右移动。我希望它保留在原处(而不是强迫它结束)。这次txtSearchTerm.Select(...)活动我没有任何运气,但我想我可能会错过一些事情...

有一个TextChanged事件,但是它仅调用我编写的搜索函数,该函数会在用户键入时填充列表框,因此为简单起见,我将省略该代码。

我是否缺少某些东西或忽略了一些使此TextBox / ListBox组合函数达到预期目的的方法?

快速说明:如果您曾经使用过UltraEdit,则基本上是在尝试模仿该配置窗口的行为。

Rez*_*aei 5

您应该使用e.Handled = true;来取消使用已处理的密钥:

private void txtSearchTerm_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Down)
    {
        if (Results.SelectedIndex < (Results.Items.Count - 1))
            Results.SelectedIndex++;
        e.Handled = true;
    }
    else if (e.KeyCode == Keys.Up)
    {
        if (Results.SelectedIndex > 0)
            Results.SelectedIndex--;
        e.Handled = true;
    }
}
Run Code Online (Sandbox Code Playgroud)

我设置e.Handled = true;了按键是Keys.Down还是,Keys.Up无论使用哪种键SelectedIndex来完全禁用移动插入符号。