【实例简介】
串口读取发送数据
【实例截图】
【核心代码】
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Net.Sockets;
using System.Net;
using System.IO.Ports;
using System.Threading;
using System.IO;
using System.Text .RegularExpressions ;
namespace Ex13_01
{
#region Public Enumerations
public enum DataMode { Text, Hex }
public enum LogMsgType { Incoming, Outgoing, Normal, Warning, Error };
#endregion
public partial class Form1 : Form
{
public string ComValue;
public string RESULT;
public int Port;
public Form1()
{
InitializeComponent();
Form.CheckForIllegalCrossThreadCalls = false;
}
private void Form1_Load(object sender, EventArgs e)
{
//read();
m_sp.PortName = "COM1";
m_sp.BaudRate = 9600; //比特率
m_sp.DataBits = 8;
m_sp.Parity = Parity.None; //校验位
m_sp.StopBits = StopBits.One; //停止位
m_sp.Handshake = Handshake.None;
listView_Chat.View = View.Details;
listView_Chat.GridLines = true;
listView_Chat.Columns.Add("Chat", 188, HorizontalAlignment.Center);
listView_Chat.Columns.Add("Time", 113, HorizontalAlignment.Center);
comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;
comboBox1.Items.AddRange(System.IO.Ports.SerialPort.GetPortNames());
}
private void btnsend_Click_1(object sender, EventArgs e) //发送消息
{
string senStr;
senStr = textBox1.Text;
try
{
//SendMsg(senStr);
m_sp.Write(senStr);
Message_Blue(senStr);
}
catch (Exception)
{
Message_Red("发送失败");
}
if (listView_Chat.Items.Count > 16)
{
listView_Chat.Items.Clear();
}
}
public void Message_Red(string Message) //红色字体消息
{
ListViewItem Show_Red = new ListViewItem(Message);