C# SerialPort实现串口通讯的代码详解

  using System.IO.Ports;

  namespace SCOM

  {

  public partial class FrmMain : Form

  {

  SerialPort serialPort;

  public FrmMain()

  {

  InitializeComponent();

  Init();

  }

  private void LoadPorts()

  {

  cboPort.Items.Clear();

  string[] port = System.IO.Ports.SerialPort.GetPortNames();

  foreach (var item in port)

  {

  cboPort.Items.Add(item);

  }

  cboPort.SelectedIndex = 0;

  }

  private void Init()

  {

  LoadPorts();

  object[] baudRate = { 4800, 9600, 19200, 38400, 57600, 115200, 230400 };

  cboBaudRate.Items.AddRange(baudRate);

  cboBaudRate.SelectedIndex = 1;

  cboDataBits.Items.Add(7);

  cboDataBits.Items.Add(8);

  cboDataBits.SelectedIndex = 1;

  cboStopBits.Items.Add("One");

  cboStopBits.Items.Add("OnePointFive");

  cboStopBits.Items.Add("Two");

  cboStopBits.SelectedIndex = 0;

  //Parity

  cboParity.Items.Add("None");

  cboParity.Items.Add("Even");

  cboParity.Items.Add("Mark");

  cboParity.Items.Add("Odd");

  cboParity.Items.Add("Space");

  cboParity.SelectedIndex = 0;

  cboHandshaking.Items.Add("None");

  cboHandshaking.Items.Add("XOnXOff");

  cboHandshaking.Items.Add("RequestToSend");

  cboHandshaking.Items.Add("RequestToSendXOnXOff");

  cboHandshaking.SelectedIndex = 0;

  btnClosePort.Enabled = false;

  }

  private void btnRefresh_Click(object sender, EventArgs e)

  {

  LoadPorts();

  }

  private void btnOpenPort_Click(object sender, EventArgs e)

  {

  if (serialPort == null)

  {

  serialPort = new SerialPort();

  }

  serialPort.PortName = cboPort.Text;//串口名称

  serialPort.BaudRate = int.Parse(cboBaudRate.Text); //获取或设置波特率

  serialPort.Parity = (Parity)Enum.Parse(typeof(Parity), cboParity.Text);//获取或设置校验位

  serialPort.DataBits = int.Parse(cboDataBits.Text);//获取或设置数据位默认值8

  serialPort.StopBits = (StopBits)Enum.Parse(typeof(StopBits), cboStopBits.Text);// 停止位

  serialPort.Handshake = (Handshake)Enum.Parse(typeof(Handshake), cboHandshaking.Text);// 握手协议

  serialPort.DataReceived += SerialPort_DataReceived;

  serialPort.Open();

  stsMain_lblStatus.Text = "端口已打开";

  btnOpenPort.Enabled = false;

  btnClosePort.Enabled = true;

  }

  private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)

  {

  this.Invoke(new Action(() =>

  {

  byte[] b = new byte[8];

  int A = serialPort.Read(b, 0, 8);

  string s = "";

  if (rdoHex.Checked)

  {

  s = ByteToHex(b);

  }

  else

  {

  s = System.Text.Encoding.Default.GetString(b);

  }

  txtReceive.AppendText(System.Environment.NewLine+ s);

  }));

  }

  private void btnClosePort_Click(object sender, EventArgs e)

  {

  if (serialPort != null && serialPort.IsOpen)

  {

  serialPort.DataReceived -= SerialPort_DataReceived;

  serialPort.Close();

  stsMain_lblStatus.Text = "端口已关闭";

  btnOpenPort.Enabled = true;

  btnClosePort.Enabled = false;

  }

  }

  private void btnSend_Click(object sender, EventArgs e)

  {

  if (serialPort == null || !serialPort.IsOpen)

  {

  return;

  }

  serialPort.Write(txtSend.Text);

  }

  private string ByteToHex(byte[] Bytes)

  {

  string str = string.Empty;

  foreach (byte Byte in Bytes)

  {

  str += String.Format("{0:X2}", Byte) + " ";

  }

  return str.Trim();

  }

  }

  }