[英]how to make command line in a multiline 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;
}
使用兩個文本框(文本框和列表框可能會更好),但使它們看起來像“一個”文本框。如果使用WPF,它看起來可能非常漂亮,並且至少在Windows形式下是可能的。
做一個快速測試。
並為文本框的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;
}
}
您可以嘗試以下方法:
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
}
}
}
私有void Execute(字符串命令){K2400.WriteString(command,true); textBoxK2400.Text + = K2400.ReadString()+ Environment.NewLine; }
就是這個。 我只建議“緩沖”部分文本,而不是全部,因為到最后可能會很長。 您可以將其拆分為多行,然后分成多行(即10行)。
並且不要忘記將字段設置為黑色而將文本設置為綠色,當以這種方式裝飾命令字段時,它看起來更加專業。
好吧,首先我建議使用RichTextBox。 要捕獲ENTER,您應該使用KeyPress Event。
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");
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.