1.代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO.Ports;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
CheckForIllegalCrossThreadCalls = false;
serialPort1.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
serialPort1.Encoding = Encoding.GetEncoding("GB2312");
System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;
}
/// /数据接收部分
private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)//接收函数
{
try
{
string recive_data;
recive_data = serialPort1.ReadExisting();
recive_data = returnData.ToString();
textBox1.Text += recive_data;
textBox1.AppendText("\r\n");
}
catch { }
}
/// //搜索串口部分
private void button1_Click(object sender, EventArgs e)
{
SearchAnAddSerialToComboBox(serialPort1, comboBox1);
}
private void SearchAnAddSerialToComboBox(SerialPort MyPort, ComboBox MyBox)//搜索串口函数
{ //将可用的串口号添加到ComboBox
string[] NmberOfport = new string[20];//最多容纳20个,太多会卡,影响效率
string MidString1;//中间数组,用于缓存
MyBox.Items.Clear();//清空combobox的内容
for (int i = 1; i < 20; i++)
{
try //核心是靠try和catch 完成遍历
{
MidString1 = "COM" + i.ToString(); //把串口名字赋给MidString1
MyPort.PortName = MidString1; //把MidString1赋给 MyPort.PortName
MyPort.Open(); //如果失败,后面代码不执行??
NmberOfport[i - 1] = MidString1; //依次把MidString1的字符赋给NmberOfport
MyBox.Items.Add(MidString1); //打开成功,添加到下列列表
MyPort.Close(); //关闭
MyBox.Text = NmberOfport[i - 1]; //显示最后扫描成功那个串口
}
catch { };
}
}
/// 打开串口部分
private void button2_Click(object sender, EventArgs e)
{
if (button2.Text == "打开串口")//为0时,表示关闭,此时可以进行打开操作
{
try
{
serialPort1.PortName = comboBox1.Text;//获取端口号
serialPort1.BaudRate = Convert.ToInt32(comboBox2.Text);//设置波特率
//serialPort1.Parity = Parity.None;
//serialPort1.DataBits = 8;
//serialPort1.StopBits = StopBits.One;
serialPort1.Open();//打开串口
button2.Text = " 关闭串口";
}
catch
{
MessageBox.Show("串口打开错误");
}
}
else //为1时,表示开启,此时可以进行关闭操作
{
try
{
serialPort1.Close();//关闭串口
button2.Text = "打开串口";//置位为0,表示状态为关闭
}
catch { }
}
}
/// <summary>
/// /清空显示部分
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button3_Click(object sender, EventArgs e)
{
textBox1.Clear();
}
}
}
2.工具
串口虚拟软件
串口软件,发送数据
3.效果
到此这篇关于C#串口接收程序的实现的文章就介绍到这了,更多相关C# 串口接收内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!