- private void btnSend_Click(object sender, EventArgs e) // 等待修改
- {
- if (!sp1.IsOpen) // 如果没打开
- {
- MessageBox.Show("请先打开串口!", "Error");
- return;
- }
- String strSend = txtSend.Text;
- if (radio1.Checked == true) //"16 进制发送" 按钮
- {
- // 处理数字转换, 目的是将输入的字符按空格,"," 等分组, 以便发送数据时的方便 (此处转的比较麻烦, 有高见者, 请指点!)
- string sendBuf = strSend;
- string sendnoNull = sendBuf.Trim();
- string sendNOComma = sendnoNull.Replace(',', ' '); // 去掉英文逗号
- string sendNOComma1 = sendNOComma.Replace(',', ' '); // 去掉中文逗号
- string strSendNoComma2 = sendNOComma1.Replace("0x", ""); // 去掉 0x
- strSendNoComma2.Replace("0X", ""); // 去掉 0X
- string[] strArray = strSendNoComma2.Split(' ');
- int byteBufferLength = strArray.Length;
- for (int i = 0; i <strArray.Length;i++)
- {
- if (strArray[i]=="")
- {
- byteBufferLength--;
- }
- }
- byte[] byteBuffer = new byte[byteBufferLength];
- int ii = 0;
- for (int i = 0; i < strArray.Length; i++) // 对获取的字符做相加运算
- {
- Byte[] bytesOfStr = Encoding.Default.GetBytes(strArray[i]);
- int decNum = 0;
- if (strArray[i] == "")
- {
- continue;
- }
- else
- {
- decNum = Convert.ToInt32(strArray[i], 16); //strArray[i] == 12 时, temp == 18
- }
- try // 防止输错, 使其只能输入一个字节的字符, 即只能在 txtSend 里输入 "eb 90" 等字符串, 不能输入 "123 2345" 等超出字节范围的数字
- {
- byteBuffer[ii] = Convert.ToByte(decNum);
- }
- catch (System.Exception ex)
- {
- MessageBox.Show("字节越界, 请逐个字节输入!", "Error");
- return;
- }
- ii++;
- }
- sp1.Write(byteBuffer, 0, byteBuffer.Length);
- }
- else // 以字符串形式发送时
- {
- sp1.WriteLine(txtSend.Text); // 写入数据
- }
- }
- void sp1_DataReceived(object sender, SerialDataReceivedEventArgs e)
- {
- if (sp1.IsOpen) // 严谨性
- {
- byte[] byteRead = new byte[sp1.BytesToRead]; //BytesToRead:sp1 接收的字符个数
- if (radio2.Checked) //'发送字符串'单选按钮
- {
- txtRcv.Text += sp1.ReadLine() + "\r\n"; // 注意: 回车换行必须这样写, 单独使用 "\r" 和 "\n" 都不会有效果
- sp1.DiscardInBuffer(); // 清空 SerialPort 控件的 Buffer
- }
- else //'发送 16 进制按钮'
- {
- try
- {
- Byte[] receivedData = new Byte[sp1.BytesToRead]; // 创建接收字节数组
- sp1.Read(receivedData, 0, receivedData.Length); // 读取数据
- sp1.DiscardInBuffer(); // 清空 SerialPort 控件的 Buffer
- string strRcv = null;
- for (int i = 0; i < receivedData.Length; i++) // 窗体显示
- {
来源: http://www.bubuko.com/infodetail-3402107.html