private void Form1_Load(object sender, EventArgs e)
{
var s = SerialPort.GetPortNames().OrderBy(r => r);
foreach (var item in s)
{
comCOM.Items.Add(item);
}
if (comCOM.Items.Count > )
comCOM.SelectedIndex = ; var rates = new object[] { , , , , , , };
comBaudRate.Items.AddRange(rates);
comBaudRate.SelectedIndex = ; txtDataBits.Text = ""; var paritys = Enum.GetNames(typeof(Parity));
comParity.Items.AddRange(paritys);
comParity.SelectedIndex = ; var stops = Enum.GetNames(typeof(StopBits));
comStopBits.Items.AddRange(stops);
comStopBits.SelectedIndex = ;
} private void btnOpen_Click(object sender, EventArgs e)
{
ClostCom();
toolInfo.Text = string.Empty;
try
{
serialPort1.PortName = comCOM.Text;
serialPort1.BaudRate = Math.Max(, ConvertHelper.ToInt(comBaudRate.Text));
serialPort1.DataBits = Math.Max(, ConvertHelper.ToInt(txtDataBits.Text));
serialPort1.Parity = (Parity)Enum.Parse(typeof(Parity), comParity.Text);
serialPort1.StopBits = (StopBits)Enum.Parse(typeof(StopBits), comStopBits.Text);
serialPort1.Open();
toolComState.BackColor = Color.Green;
txtInfo.Text = DateTime.Now.ToString("HH:mm") + " 打开串口成功!\r\n";
}
catch (Exception ex)
{
toolInfo.Text = "打开串口失败!";
txtInfo.Text = DateTime.Now.ToString("HH:mm") + " 打开串口失败:" + ex.Message + "\r\n";
}
} private void ClostCom()
{
try
{
serialPort1.Close();
toolComState.BackColor = SystemColors.Control;
}
catch { }
} private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
Thread.Sleep();
byte[] buffer = new byte[serialPort1.ReadBufferSize];
int len = serialPort1.Read(buffer, , buffer.Length); Invoke((MethodInvoker)delegate
{
toolInfo.Text = string.Empty;
if (txtInfo.Lines.Length > )
txtInfo.Text = string.Format("{0} {1} 接收到:{2}", DateTime.Now.ToString("HH:mm"), serialPort1.PortName, GetByte(buffer, len));
else
{
var s = txtInfo.Text;
txtInfo.Text = string.Format("{0} {1} 接收到:{2}\r\n{3}", DateTime.Now.ToString("HH:mm"), serialPort1.PortName, GetByte(buffer, len), s);
}
});
} private string GetByte(byte[] buffer, int len)
{
StringBuilder sb = new StringBuilder();
for (int i = ; i < len; i++)
{
var item = buffer[i];
sb.Append(item.ToString("x2") + " ");
}
sb.AppendLine();
sb.Append(Encoding.Default.GetString(buffer));
sb.AppendLine();
return sb.ToString();
}
有个 BUG:文本框始终只有一行内容。
虚拟串口工具下载:下载地址