我正在嘗試從串行端口讀取字節並將它們作爲字符串寫入文本框。serialport單獨讀取每個字符
我的問題是,代碼將每個字母/字符單獨寫入框中,而不是一個長字符串,所以如果我收到「你好」,它將寫入「H」,然後清除框,然後「e」。 .etc
public partial class Form1 : Form
{
static SerialPort serial;
public string line;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
inputBox.Text = "Enter some text, then press enter";
serial = new SerialPort("COM3", 9600, Parity.None, 8, StopBits.One);
serial.Open();
serial.DataReceived += new SerialDataReceivedEventHandler(serial_DataReceived);
}
public void serial_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
// wait for the buffer
System.Threading.Thread.Sleep(300);
byte[] bytes = new byte[serial.BytesToRead];
serial.Read(bytes, 0, bytes.Length);
line = System.Text.Encoding.UTF8.GetString(bytes);
if (line != null)
{
writeRecieved(line);
}
}
public void writeRecieved (string line)
{
if (outputBox.InvokeRequired)
{
outputBox.Invoke((MethodInvoker)delegate { outputBox.Text = line; });
}
else
{
outputBox.Text = line;
}
}
然而,當調試,這似乎只擊中每行的內容一次,和本地視圖顯示了可變線爲「Hello」的
編輯: 我試圖追加( outputBox.Text + = line;),但是每次收到新消息時,文本框都會填充文本。我試着把一個outputBox.Clear();在datarecieved處理程序中,但它在每個字節出於某種原因後執行此操作
爲什麼不追加字符而不是替換整個文本字符串..?爲什麼不用'outputBox.Text + = line'來代替? – Artless 2013-04-24 18:48:23