按Enter键将ListBox中的Selected Item添加到RichTextBox

时间:2013-03-04 03:18:20

标签: c# icsharpcode

与此主题相关: Hidden ListBox will appear while Typing Words in RichTextBox

我正在编写代码编辑器,我只想知道如何使用enterkey将列表框中的项目添加到文本框中。

进一步说明我的话语:

public String[] ab = { "abstract" };
public String[] am = { "AmbientProperties", "AmbientValueAttribute" };

样品:

在richtextbox(rtb)中,我输入Ab,然后hiddenlistbox将使用此代码显示“抽象”文本(已经这样做):

if (token == "letterA" || token.StartsWith("Ab") || token.StartsWith("ab"))
{
    int length = line.Length - (index - start);
    string commentText = rtb.Text.Substring(index, length);
    rtb.SelectionStart = index;
    rtb.SelectionLength = length;
    lb.Visible = true;

    KeyWord keywordsHint = new KeyWord();

    foreach (string str in keywordsHint.ab)
    {
        lb.Items.Add(str);
    }
    break;
}

然后在按下enterkey后我想将列表框中的摘要添加到richtextbox。

  

RichTextBox声明为rtb,ListBox声明为lb

我该怎么办?谢谢。

2 个答案:

答案 0 :(得分:2)

某些控件在按键事件中按下时无法识别某些按键。 例如,ListBox无法识别按下的键是否为Enter键。

请参阅以下链接中的备注部分 - http://msdn.microsoft.com/en-us/library/system.windows.forms.control.keydown(v=vs.110).aspx

您的问题的解决方案之一可以 http://msdn.microsoft.com/en-us/library/system.windows.forms.control.previewkeydown(v=vs.110).aspx

为列表框实现PreviewKeyDown事件,以便列表框识别您的操作。

以下是示例代码段 -

    private void listBox1_KeyDown(object sender, KeyEventArgs e)
    {

        if (e.KeyCode == Keys.Enter)
        {
            //Do your task here :)
        }
    }

    private void listBox1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
    {
        switch (e.KeyCode)
        {
            case Keys.Enter:
                e.IsInputKey = true;
                break;
        }
    }

答案 1 :(得分:0)

您不能直接在列表框中键入文本,因此我使用textBox创建了一个示例:

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar == 13)
    {
        this.richTextBox1.AppendText((sender as TextBox).Text);
        e.Handled = true;
    }
}

如果你的意思是comboBox,你可以很容易地调整它,替换上面的行:

private void comboBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar == 13)
    {
        this.richTextBox1.AppendText((sender as ComboBox).Text);
        e.Handled = true;
    }
}

将选定的列表框条目复制到rtf框:

private void listBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar == 13)
    {
        foreach (string s in listBox1.SelectedItems)
        {
            this.richTextBox1.AppendText(s + Environment.NewLine);
        }

        e.Handled = true;
    }
}