我的窗户上有两个按钮。
通过单击停止按钮,程序将停止保存数据,但仍会显示文本框中串行端口的传入数据。有人可以帮忙吗?我的启动和停止按钮代码如下:
private void buttonStart_Click(object sender, EventArgs e)
{
serialPort1.PortName = pp.get_text();
string Brate = pp.get_rate();
serialPort1.BaudRate = Convert.ToInt32(Brate);
serialPort1.Open();
if (serialPort1.IsOpen)
{
buttonStart.Enabled = false;
buttonStop.Enabled = true;
textBox1.ReadOnly = false;
}
}
private void buttonStop_Click(object sender, EventArgs e)
{
string Fname = pp.get_filename();
System.IO.File.WriteAllText(Fname, this.textBox1.Text);
}
答案 0 :(得分:1)
1)您需要注册到串行端口的DataRecieved事件以接收来自SerialPort实例的响应。
sp = new SerialPort();
sp.DataReceived += sp_DataReceived;
然后,在sp_DataRecieved中:
void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
// this the read buffer
byte[] buff = new byte[9600];
int readByteCount = sp.BaseStream.Read(buff, 0, sp.BytesToRead);
// you can specify other encodings, or use default
string response = System.Text.Encoding.UTF8.GetString(buff);
// you need to implement AppendToFile ;)
AppendToFile(String.Format("response :{0}",response));
// Or, just send sp.ReadExisting();
AppendToFile(sp.ReadExisting());
}
2)如果SerialPort实例的读缓冲区中仍有数据,您将收到数据。关闭端口后,您需要从DataReceived事件中取消注册。
sp -= sp_DataRecieved;
<强>更新强>
您可以使用此方法附加到文件
private void AppendToFile(string toAppend)
{
string myFilePath = @"C:\Test.txt";
File.AppendAllText(myFilePath, toAppend + Environment.NewLine);
}