列表框在“' 1'按了

时间:2018-05-22 02:13:36

标签: c# winforms listbox

我正在使用ListBox创建应用程序。我希望用户能够点击它,开始输入,并看到他们的文字出现在该项目中。以下是几乎可行的简化版本:

using System.Windows.Forms;

namespace ListboxTest
{
    public partial class ListboxTest : Form
    {
        InitializeComponent();
        listBox1.Items.Add("");
        listBox1.Items.Add("");
        listBox1.KeyPress += new KeyPressEventHandler(ListBoxKeyPress);
    }

    private void ListBoxKeyPress(object sender, KeyPressEventArgs e)
    {
        ListBox lbx = (ListBox)sender;
        if (lbx.SelectedIndices.Count != 1)
            return;

        int temp = lbx.SelectedIndex;
        string value = lbx.Items[temp].ToString();
        value += e.KeyChar;

        lbx.Items[temp] = value;
    }
}

选择ListBox后,用户可以开始输入并查看显示的文本。一切都按预期工作,直到发生两件事:

  1. 用户从一个项目切换到另一个项目(点击进入不同的输入或使用向上/向下箭头),然后是
  2. 用户按下与未选择项目名称中第一个字符对应的键。
  3. 从那时起,每当用户按下该键时(在我的情况下,' 1'),ListBox的所选项目就会发生变化。只有两件物品 (均以' 1'开头),按' 1'导致ListBox将所选项从索引0切换到索引1(反之亦然)。

    我已经尝试了一下,这就是我发现的。

    • 只有当我按下' 1时才会出现这种情况。没有其他数字,数字或标点符号会导致这种情况。对于ListBox项目开头的任何字符都会发生这种情况。
    • 如果ListBox有两个以上的项目,它将循环显示所有先前输入的具有相同起始字符的元素。将跳过从未选择过的项目。

    我尝试过的事情:

    • ListBox.SetSelected(int index, bool selected)
    • 清算所选索引
    • ListBox.ClearSelected()
    • 清算所选索引
    • Listbox.SelectionMode设为SelectionMode.One

    我使用的是VS 2015 Professional,Windows 7 SP1(x64),C#6.0,以及针对.NET 4.6.1。

    所以,我的问题:发生了什么以及我该如何解决?

2 个答案:

答案 0 :(得分:2)

如果在Listbox处于焦点时键入任何键盘键,它实际遍历其所有项目并选择以键入键开头的那些项目(逐个)。所以它是Listbox的基本行为。

您需要在此处使用KeyEventArgs.SuppressKeyPress属性,因为您需要在KeyEvenArgs获取KeyDown的情况下编写逻辑,例如 private void lstBoxItems_KeyDown(object sender, KeyEventArgs e) { ListBox lbx = (ListBox)sender; if (lbx.SelectedIndices.Count != 1) return; e.SuppressKeyPress = true; //calling this method to get char from key data char keyChar = GetChar(e); int temp = lbx.SelectedIndex; string value = lbx.Items[temp].ToString(); value += keyChar; lbx.Items[temp] = value; }

尝试以下代码

    char GetChar(KeyEventArgs e)
    {
        int keyValue = e.KeyValue;
        if (!e.Shift && keyValue >= (int)Keys.A && keyValue <= (int)Keys.Z)
            return (char)(keyValue + 32);
        return (char)keyValue;
    }

并添加此方法

Filename    Filesize   Filepath
---------   ---------  ---------
test1.exe   5kb        /home/program/
test2.exe   6kb        /home/program/
test3.mp3   10mb       /home/music/
test4.avi   15mb       /home/video/

4 files are removed

我搜索了一些其他问题,你可以参考,

How to disable listbox auto select item when pressing key

我有从这里将密钥数据转换为char的方法。

Get the char on Control.KeyDown?

答案 1 :(得分:0)

感谢Amit指出我正确的方向。这是ListBox的默认行为。但是,使用事件处理程序实际上是一种更容易抑制此行为的方法。

使用事件处理程序&#34; KeyPress&#34;时,您可以设置 e.Handled = truesuppress further processing。这可以防止列表框在键入时选择其他项目。