我正在尝试从串行端口读取字节并将它们作为字符串写入文本框。
我的问题是代码将每个字母/字符单独写入框中,而不是一个长字符串,所以如果我收到“Hello”它将写“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 处理程序中,但由于某种原因它在每个字节之后执行此操作