如何在多行TextBox中创建命令行

时间:2011-10-25 13:21:57

标签: c# command-line textbox

我正在使用GPIB处理一些电子仪器。我可以用这样的乐器进行交流:

K2400.WriteString("*IDN?", true);
textBoxK2400.Text += K2400.ReadString() + Environment.NewLine;

第一行将执行命令,在第二行中,我将最后一个命令的响应添加到文本框中。如何直接在文本框中编写命令并添加响应?

例如,如果在“>>”之类的指标后输入用户命令并按ENTER键,响应应添加到文本框的下一行。

那么如何阅读文本框的最后一行并在新行中添加响应?我正在寻找一种方法:

private void Execute(string command)
{
  K2400.WriteString(command, true);
  textBoxK2400.Text += K2400.ReadString() + Environment.NewLine;
}

4 个答案:

答案 0 :(得分:5)

使用两个文本框(文本框和列表框可能更好),但让它们看起来像“一个”文本框..如果使用WPF,它看起来非常好,至少可能是Windows形式。

做了快速测试..

enter image description here

使用此代码用于文本框的KeyPress事件:

    private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (e.KeyChar == (char)Keys.Return)
        {
            listBox1.Items.Add(textBox1.Text);
            textBox1.Text = String.Empty;
            listBox1.SelectedIndex = listBox1.Items.Count - 1;
        }
    }

答案 1 :(得分:1)

你可以试试这个:

private void textBoxK2400_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Return)
    {
        string command = textBoxK2400.Text.Split('\n').LastOrDefault();
        if (!String.IsNullOrEmpty(command) && command.StartsWith(">>"))
        {
            K2400.WriteString(command.Substring(2), true);
            textBoxK2400.Text += K2400.ReadString() + Environment.NewLine;
            textBoxK2400.Text += ">>"; // It's not necessary
        }
    }
}

答案 2 :(得分:1)

  

private void Execute(string command){K2400.WriteString(command,   真正); textBoxK2400.Text + = K2400.ReadString()+ Environment.NewLine;   }

就是这样。我只是建议“缓冲”部分文本,而不是全部,因为它可能会很长时间。您可以将它拆分为之前的行并采用多行(即10)。

并且不要忘记使字段变黑并且文本变为绿色,当命令字段以这样的方式进行装饰时,它看起来更专业。

答案 3 :(得分:0)

首先,我建议使用RichTextBox。 要捕获ENTER,您应该使用KeyPress事件。

private void richTextBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Enter)
            { 
                string LastLine = richTextBox1.Lines[richTextBox1.Lines.Length-2];
                if (LastLine.StartsWith(">>"))
                {
                    //here you can filter the LastLine
                    K2400.WriteString(LastLine, true);
                    richTextBox1.AppendText(K2400.ReadString() + Environment.NewLine);
                }
                else
                {
                    //here you can unwrite the last line
                    string[] totalLines = richTextBox1.Lines;
                    richTextBox1.Text = "";
                    for (int i = 0; i < totalLines.Length - 2; i++)
                    {
                        richTextBox1.AppendText(totalLines[i]+Environment.NewLine);
                    }
                    MessageBox.Show("That was not a valid command");
                }
            }
        }
相关问题