定義:異步
SerialPort ComDevice = new SerialPort();ui
在開啓串口前 設置先後文本轉換的字符編碼 this
代碼:ComDevice.Encoding = System.Text.Encoding.GetEncoding("GB2312");//此行很是重要 可解決接收中文亂碼問題編碼
接收代碼:orm
#region 串口相關操做 SerialPort ComDevice = new SerialPort(); private void GetComList() { //獲取可用串口列表 string[] ports = SerialPort.GetPortNames(); foreach (string port in ports) { cbbComList.Properties.Items.Add(port); } if (cbbComList.Properties.Items.Count > 0) { cbbComList.SelectedIndex = 0; cbbComList.Enabled = true; } } private void btnComOpen_Click(object sender, EventArgs e) { if (btnComOpen.Tag.ToString() == "0") { ComDevice.PortName = cbbComList.SelectedItem.ToString(); ComDevice.BaudRate = 115200; ComDevice.Parity = (Parity)0; ComDevice.DataBits = 8; ComDevice.StopBits = (StopBits)1; ComDevice.Encoding = System.Text.Encoding.GetEncoding("GB2312");//此行很是重要 可解決接收中文亂碼問題 try { ComDevice.Open(); } catch (Exception ex) { MessageBox.Show(ex.Message, "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } btnComOpen.Text = "關 閉"; btnComOpen.Tag = "1"; picComStatus.Image = Properties.Resources.green; ComDevice.DataReceived += new SerialDataReceivedEventHandler(ComDevice_DataReceived); } else { try { ComDevice.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message, "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error); } btnComOpen.Text = "打 開"; btnComOpen.Tag = "0"; picComStatus.Image = Properties.Resources.red; } } /// <summary> /// 發送數據 ---此代碼在發送時都是轉換成十六進制進行發送 /// </summary> private void Send(string cmd, bool HexCmd) { if (cmd == null) return; if (cmd.Length > 0) { if (ComDevice.IsOpen == true) { byte[] SendBytes = null; string SendData = cmd; if (HexCmd == true) { //16進制發送 try { //剔除全部空格 SendData = SendData.Replace(" ", ""); if (SendData.Length % 2 == 1) {//奇數個字符 SendData = SendData.Remove(SendData.Length - 1, 1);//去除末位字符 } List<string> SendDataList = new List<string>(); for (int i = 0; i < SendData.Length; i = i + 2) { SendDataList.Add(SendData.Substring(i, 2)); } SendBytes = new byte[SendDataList.Count]; for (int j = 0; j < SendBytes.Length; j++) { SendBytes[j] = (byte)(Convert.ToInt32(SendDataList[j], 16)); } } catch { XtraMessageBox.Show("請輸入正確的16進制數據!", "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error); } } else { System.Text.Encoding chs = System.Text.Encoding.GetEncoding("gb2312"); byte[] bytes = chs.GetBytes(cmd); string str = ""; for (int i = 0; i < bytes.Length; i++) { str += string.Format("{0:X2}", bytes[i]); } List<string> SendDataList = new List<string>(); for (int i = 0; i < str.Length; i = i + 2) { SendDataList.Add(str.Substring(i, 2)); } SendDataList.Add("0D"); SendBytes = new byte[SendDataList.Count]; for (int j = 0; j < SendBytes.Length; j++) { SendBytes[j] = (byte)(Convert.ToInt32(SendDataList[j], 16)); } } ComDevice.Write(SendBytes, 0, SendBytes.Length);//發送數據 } else { XtraMessageBox.Show("請打開串口!", "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } #region 接收數據 private void ComDevice_DataReceived(object sender, SerialDataReceivedEventArgs e) { UpdateRecevie(ComDevice.ReadExisting()); } public delegate void UpdateString(object NewData); public void UpdateRecevie(object NewData) { if (this.InvokeRequired)//等待異步 { UpdateString _myInvoke = new UpdateString(UpdateRecevie); this.Invoke(_myInvoke, new object[] { NewData }); } else { txtComReceive.AppendText(NewData.ToString()); txtComReceive.SelectionStart = txtComReceive.Text.Length - 1; txtComReceive.ScrollToCaret(); } } #endregion