C# 按Enter键将所选项目从ListBox添加到RichTextBox

C# 按Enter键将所选项目从ListBox添加到RichTextBox,c#,icsharpcode,C#,Icsharpcode,与本主题相关: 我正在开发一个代码编辑器,我只想知道如何使用enterkey将列表框中的项目添加到文本框中 更进一步,这里是我的字符串: public String[] ab = { "abstract" }; public String[] am = { "AmbientProperties", "AmbientValueAttribute" }; 样本: 在richtextbox(rtb)中,我键入Ab,然后hiddenlistbox将显示“抽象”文本(已经这样做了),使用以下代码: i

与本主题相关:

我正在开发一个代码编辑器,我只想知道如何使用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;
}
然后,在按下Enter键之后,我想将摘要从listbox添加到richtextbox

RichTextBox声明为rtb,ListBox声明为lb


我该怎么办?谢谢。

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

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;
    }
}

在按键按下事件中,某些控件无法识别某些按键。 对于eg ListBox,不识别按键是否为Enter键

请参阅以下链接中的备注部分-

解决问题的方法之一是

为listbox实现PreviewKeyDown事件,以便listbox识别您的操作

以下是示例代码片段-

    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;
        }
    }

或者可以从列表框双击?system.windows.Forms.combobox不包含所选项目的定义,并且没有扩展方法“selecteditems”接受类型的第一个参数。这次我将列表框更改为combobox。没有更多的列表框。现在从combobox中选择的内容将添加到richtextbox上的文本。先生,我该怎么做?