但是这样子写我返回的数据就不是我想的那样!应该是这样才对图片说明!但是他实际是这样图片说明
void sp1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
if (sp1.IsOpen)
{
//输出当前时间
//DateTime dt = DateTime.Now;
//txtReceive.Text += dt.GetDateTimeFormats('f')[0].ToString() + "\r\n";
txtReceive.SelectAll();
txtReceive.SelectionColor = Color.Blue; //改变字体的颜色
byte[] byteRead = new byte[sp1.BytesToRead]; //BytesToRead:sp1接收的字符个数
if (rdSendStr.Checked) //'发送字符串'单选按钮
{
txtReceive.Text += sp1.ReadLine() + "\r\n";
sp1.DiscardInBuffer();
}
else //'发送16进制按钮'
{
try
{
Byte[] receivedData = new Byte[sp1.BytesToRead]; //创建接收字节数组
sp1.Read(receivedData, 0, receivedData.Length); //读取数据
//string text = sp1.Read(); //Encoding.ASCII.GetString(receivedData);
sp1.DiscardInBuffer(); //清空SerialPort控件的Buffer
string strRcv = null;
for (int i = 0; i < receivedData.Length; i++) //窗体显示
{
strRcv += receivedData[i].ToString("X2"); //16进制显示
}
txtReceive.Text += strRcv + "\r\n";
System.IO.File.WriteAllText("file.txt", txtReceive.Text);
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message, "出错提示");
txtSend.Text = "";
}
//FileStream fs = new FileStream(@"D:\text.txt", FileMode.Append);
//StreamWriter sw = new StreamWriter(fs, Encoding.Default);
//sw.WriteLine(txtReceive.Text);
//sw.Close();
//fs.Close();
}
}
else
{
MessageBox.Show("请打开某个串口", "错误提示");
}
}