c#串口实例
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using System.Threading;
using System.Collections;
using System.IO;
namespace COM_A
{
public partial class Form1 : Form
{
public byte[] myBy;//传递串口接收到的数据
public int myByLenth = 0;//串口接收到的数据长度
public string myStr;//串口接收的字符串
public bool receiveDtatFlag = false;
public int send_count = 0;
public Form1()
{
InitializeComponent();
this.ControlBox = false;//最小化最大化关闭按钮处理
}
private void Form1_Load(object sender, EventArgs e)//页面加载
{
#region 串口设置初始化加载
try
{
foreach (string com in System.IO.Ports.SerialPort.GetPortNames())//串口检测
comboBox1.Items.Add(com);
//comboBox1.Text = (string)comboBox1.Items[0];//初始化选择串口
comboBox1.Text = myConfing.ConfingGetValue("COM");//使用配置文件加载
if (comboBox1.Text == "")
{
comboBox1.Text = (string)comboBox1.Items[0];//初始化选择串口
}
}
catch (Exception er)
{
MessageBox.Show("端口加载失败!" er.Message, "提示");
}
//列出常用的波特率
string[] ss = new string[] { "1200", "2400", "4800", "9600", "19200", "38400", "43000", "56000", "57600", "115200" };
comboBox2.DataSource = ss;
/*for (int temp = 0; temp < 10; temp )
{
comboBox2.Items.Add(ss[temp]);
}*/
comboBox2.Text = myConfing.ConfingGetValue("buadRate");
if (comboBox2.Text == "")
{
comboBox2.SelectedIndex = 9;
}
//comboBox2.SelectedIndex = 3;
//列出奇偶校验位
comboBox3.DataSource = Enum.GetNames(typeof(Parity));
//comboBox3.Items.Add("无校验");
//comboBox3.Items.Add("奇校验");
//comboBox3.Items.Add("偶校验");
//comboBox3.SelectedIndex = 0;
comboBox3.Text = myConfing.ConfingGetValue("Parity");
if (comboBox3.Text == "")
{
comboBox3.Text = "None";
}
//列出数据位
ss = new string[] { "5", "6", "7", "8", "9", "10" };
comboBox4.DataSource = ss;
//comboBox4.Text = "8";
comboBox4.Text = myConfing.ConfingGetValue("dataBits");
if (comboBox4.Text == "")
{
comboBox4.SelectedIndex = 3;
}
//列出停止位
comboBox5.DataSource = Enum.GetNames(typeof(StopBits));
//comboBox5.Text = Enum.Format(typeof(StopBits), StopBits.One, "G");
comboBox5.Text = myConfing.ConfingGetValue("stopBits");
if (comboBox5.Text == "")
{
comboBox5.SelectedIndex = 1;
}
button1.Text = "打开串口";
//开始执行后台操作
//backgroundWorker1.RunWorkerAsync();
checkBox1.Checked = false;
checkBox2.Checked = true;
checkBox3.Checked = true;
checkBox4.Checked = false;
#endregion
//this.button3.Visible = false;
}
private void comboBox1_DropDown_1(object sender, EventArgs e)
{
try
{
comboBox1.Items.Clear();
foreach (string com in System.IO.Ports.SerialPort.GetPortNames())//串口检测
comboBox1.Items.Add(com);
}
catch (Exception er)
{
MessageBox.Show("端口加载失败!" er.Message, "提示");
}
}
#region 打开串口按钮处理
public void RefrespictureBox1()//刷新打开串口按键显示以及颜色
{
if (serialPort1.IsOpen)
{
button1.BackColor = SystemColors.GradientActiveCaption;
button1.Text = "关闭串口";
}
else
{
button1.BackColor = SystemColors.Control;
button1.Text = "打开串口";
}
myConfing.SetValue("COM", comboBox1.Text);
myConfing.SetValue("buadRate", comboBox2.Text);
myConfing.SetValue("Parity", comboBox3.Text);
myConfing.SetValue("dataBits", comboBox4.Text);
myConfing.SetValue("stopBits", comboBox5.Text);
}
private void button1_Click(object sender, EventArgs e)//打开串口
{
try
{
if (serialPort1.IsOpen)//如果串口是开的则关闭
{
serialPort1.Close();
comboBox1.Enabled = true;
comboBox2.Enabled = true;
comboBox3.Enabled = true;
comboBox4.Enabled = true;
comboBox5.Enabled = true;
#region
//button1.Text = "打开串口";
/*//关闭串口后,串口设置选项便可以继续使用
comboBox1.Enabled = true;
comboBox2.Enabled = true;
comboBox3.Enabled = true;
comboBox4.Enabled = true;
comboBox5.Enabled = true;*/
#endregion
}
else//否则打开串口
{
//button1.Text = "关闭串口";
serialPort1.PortName = comboBox1.Text;
serialPort1.BaudRate = Convert.ToInt32(comboBox2.Text);
serialPort1.Parity = (Parity)Enum.Parse(typeof(Parity), comboBox3.Text);
serialPort1.DataBits = Int32.Parse(comboBox4.Text);
serialPort1.StopBits = (StopBits)Enum.Parse(typeof(StopBits), comboBox5.Text);
serialPort1.Encoding = Encoding.GetEncoding("Gb2312");//返回与指定代码页名称关联的编码Gb2312
serialPort1.Open();
comboBox1.Enabled = false;
comboBox2.Enabled = false;
comboBox3.Enabled = false;
comboBox4.Enabled = false;
comboBox5.Enabled = false;
}
RefrespictureBox1();//刷新打开串口按键显示以及颜色
}
catch (Exception)
{
//打开串口失败后,相应标志位取消
MessageBox.Show("串口无效或已被占用!", "错误提示");
}
}
#endregion
#region 发送区形式处理、串口按键发送、定时自动发送以及其他外部调用发送相关接口
private bool CheckSendData()//检查串口发送区域
{
if (textBox2.Text.Trim() == "") return false;
return true;
}
private void checkBox4_CheckedChanged(object sender, EventArgs e)//发送区HEX处理
{
string s = "";
if (checkBox4.CheckState == CheckState.Checked)//发送HEX显示
{
byte[] by = Encoding.GetEncoding("Gb2312").GetBytes(textBox2.Text);
textBox2.Text = "";
foreach (byte btmp in by)
{
s = "00" string.Format("{0:X}", btmp);
textBox2.Text = s.Substring(s.Length - 2, 2);
textBox2.Text = " ";
}
}
else//发送ASCII显示
{
ArrayList al = myClass.Str16ToArrayList(textBox2.Text);
byte[] by = new byte[al.Count];
int i = 0;
foreach (string stmp in al)
{
by[i] = Convert.ToByte(stmp, 16);
i ;
}
textBox2.Text = Encoding.GetEncoding("Gb2312").GetString(by);
}
}
private void textBox2_KeyPress(object sender, KeyPressEventArgs e)//发送区有按键键入,
{
if (checkBox1.CheckState == CheckState.Checked)//HEX发送时
{
if (!Uri.IsHexDigit(e.KeyChar) && e.KeyChar != ' ')//不符合HEX的键入清除
{
e.KeyChar = (char)0;
}
}
}
private void button2_Click(object sender, EventArgs e)//按键发送
{
try
{
if (serialPort1.IsOpen)
{
/*if (!CheckSendData())//检测要发送的数据
{
MessageBox.Show("请输入要发送的数据!", "错误提示");
return;
}*/
string s = "";
//MessageBox.Show(checkBox4.Checked.ToString());
if (checkBox4.Checked)//十六进制发送
{
ArrayList al = myClass.Str16ToArrayList(textBox2.Text);
byte[] by = new byte[al.Count];
int i = 0;
foreach (string stmp in al)
{
by[i] = Convert.ToByte(stmp, 16);//将指定基的数字的字符串表示形式转换为等效的 8 位无符号整数。
i ;
}
serialPort1.Write(by, 0, i);//发送字节
//s = Encoding.GetEncoding("Gb2312").GetString(by);//在派生类中重写时,将指定字节数组中的所有字节解码为一个字符串。。
}
else//ASCII发送
{
s = textBox2.Text;
serialPort1.Write(s);//串口发送字符串
}
//MessageBox.Show(s);
}
else
{
MessageBox.Show("串口未打开!", "错误提示");
}
}
catch (Exception)
{
MessageBox.Show("发送数据时发生错误!", "错误提示");
}
}
public void sendData(string dataIn)//调用的发送函数
{
try
{
if (serialPort1.IsOpen)
{
/*if (!CheckSendData())//检测要发送的数据
{
MessageBox.Show("请输入要发送的数据!", "错误提示");
return;
}*/
string s = "";
textBox2.Text = dataIn;
//MessageBox.Show(checkBox4.Checked.ToString());
if (checkBox4.Checked)//十六进制发送
{
ArrayList al = myClass.Str16ToArrayList(textBox2.Text);
byte[] by = new byte[al.Count];
int i = 0;
foreach (string stmp in al)
{
by[i] = Convert.ToByte(stmp, 16);//将指定基的数字的字符串表示形式转换为等效的 8 位无符号整数。
i ;
}
serialPort1.Write(by, 0, i);//发送字节
//s = Encoding.GetEncoding("Gb2312").GetString(by);//在派生类中重写时,将指定字节数组中的所有字节解码为一个字符串。。
}
else//ASCII发送
{
s = textBox2.Text;
serialPort1.Write(s);//串口发送字符串
}
//MessageBox.Show(s);
}
else
{
MessageBox.Show("串口未打开!", "错误提示");
}
}
catch (Exception)
{
MessageBox.Show("发送数据时发生错误!", "错误提示");
}
}
public void sendData_NoDispaly(string dataIn)//调用的发送函数并且不显示在发送区域
{
try
{
if (serialPort1.IsOpen)
{
/*if (!CheckSendData())//检测要发送的数据
{
MessageBox.Show("请输入要发送的数据!", "错误提示");
return;
}*/
string s = "";
//textBox2.Text = dataIn;//不显示在发送区域
//MessageBox.Show(checkBox4.Checked.ToString());
if (checkBox4.Checked)//十六进制发送
{
ArrayList al = myClass.Str16ToArrayList(textBox2.Text);
byte[] by = new byte[al.Count];
int i = 0;
foreach (string stmp in al)
{
by[i] = Convert.ToByte(stmp, 16);//将指定基的数字的字符串表示形式转换为等效的 8 位无符号整数。
i ;
}
serialPort1.Write(by, 0, i);//发送字节
//s = Encoding.GetEncoding("Gb2312").GetString(by);//在派生类中重写时,将指定字节数组中的所有字节解码为一个字符串。。
}
else//ASCII发送
{
s = textBox2.Text;
serialPort1.Write(s);//串口发送字符串
}
//MessageBox.Show(s);
}
else
{
MessageBox.Show("串口未打开!", "错误提示");
}
}
catch (Exception)
{
MessageBox.Show("发送数据时发生错误!", "错误提示");
}
}
private void timer1_Tick(object sender, EventArgs e)//定时自动发送
{
timer1.Interval = Convert.ToInt32(textBox1.Text);
try
{
if ((serialPort1.IsOpen) && (checkBox5.Checked == true))
{
/*if (!CheckSendData())//检测要发送的数据
{
MessageBox.Show("请输入要发送的数据!", "错误提示");
return;
}*/
string s = "";
//textBox2.Text = dataIn;
//MessageBox.Show(checkBox4.Checked.ToString());
if (checkBox4.Checked)//十六进制发送
{
ArrayList al = myClass.Str16ToArrayList(textBox2.Text);
byte[] by = new byte[al.Count];
int i = 0;
foreach (string stmp in al)
{
by[i] = Convert.ToByte(stmp, 16);//将指定基的数字的字符串表示形式转换为等效的 8 位无符号整数。
i ;
}
serialPort1.Write(by, 0, i);//发送字节
//s = Encoding.GetEncoding("Gb2312").GetString(by);//在派生类中重写时,将指定字节数组中的所有字节解码为一个字符串。。
}
else//ASCII发送
{
s = textBox2.Text;
serialPort1.Write(s);//串口发送字符串
}
send_count ;
textBox5.Text = send_count.ToString();
}
else
{
//MessageBox.Show("串口未打开!", "错误提示");
}
}
catch (Exception)
{
//MessageBox.Show("发送数据时发生错误!", "错误提示");
}
}
#endregion
#region 接收方法一用到的线程处理,不用
delegate void SetTextCallback(string text);//委托,使用回调函数时考虑使用
private void SetText(string text)
{
try
{
if (this.richTextBox1.InvokeRequired)//获取一个值,该值指示调用方在对控件进行方法调用时是否必须调用 Invoke 方法,因为调用方位于创建控件所在的线程以外的线程中。
{
SetTextCallback d = new SetTextCallback(SetText);//回调函数
this.Invoke(d, new object[] { text });//执行delegate里的搭载函数
}
else
{
this.richTextBox1.Text = text;
}
//this.richTextBox2.Focus();//获取焦点
//this.richTextBox2.Select(this.richTextBox2.TextLength, 0);//光标定位到文本最后
/* //设定光标所在位置
this.richTextBox1.SelectionStart = richTextBox1.TextLength;
//滚动到当前光标处
this.richTextBox1.ScrollToCaret();*/
}
catch (Exception)
{
}
}
#endregion
#region 串口接收处理
//int receive_count_test = 0;
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)//清除接收
{
richTextBox1.Text = "";
send_count = 0;
//receive_count_test = 0;
//textBox5.Text = "";
//textBox5.Text = "";
}
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)//接收事件触发
{
#region
/* char[] c;
//StringBuilder builder = new StringBuilder();//避免在事件处理方法中反复的创建,定义到外面。
try
{
if (serialPort1.IsOpen)
{
c = new char[serialPort1.BytesToRead];
serialPort1.Read(c, 0, c.Length);//串口读取
if (c.Length > 0)
{
if (checkBox1.Checked)//接收HEX显示
{
if (checkBox3.Checked)//接收时间显示
{
SetText(DateTime.Now.ToString());
SetText(" ");
}
byte[] by = Encoding.GetEncoding("Gb2312").GetBytes(c);
myBy = by;
myByLenth = by.Length;
/*if (by[0] == 0x7b)
{
MessageBox.Show("正确");
}
else
{
MessageBox.Show(by[0].ToString());
}*
foreach (byte btmp in by)
{
string s = "00" string.Format("{0:X}", btmp);//将指定字符串中的一个或多个格式项替换为指定对象的字符串表示形式
s = s.Substring(s.Length - 2, 2);
SetText(new string(s.ToCharArray()));
SetText(" ");
}
if (checkBox2.Checked)//接收换行显示
{
SetText("\n");
}
}
else
{
if (checkBox3.Checked)//接收时间显示
{
SetText(DateTime.Now.ToString());
}
SetText(new string(c));
if (checkBox3.Checked)//接收换行显示
{
SetText("\n");
}
}
//this.richTextBox2.Text = "\n";
}
}
}
catch (Exception)
{
}
if (checkBox2.Checked)//接收HEX显示
{
Thread.Sleep(500);//延时500ms 等待接收完数据
}
else
{
Thread.Sleep(10);//延时100ms 等待接收完数据
}*/
/* //设定光标所在位置
this.richTextBox1.SelectionStart = richTextBox1.TextLength;
//滚动到当前光标处
this.richTextBox1.ScrollToCaret();*/
//追加的形式添加到文本框末端,并滚动到最后。
//this.richTextBox1.AppendText(builder.ToString());
#endregion
#region
Thread.Sleep(Convert.ToInt32(textBox5.Text.Trim()));//延时100ms 等待接收完数据
//第二种接收方式
StringBuilder builder = new StringBuilder();//避免在事件处理方法中反复的创建,定义到外面。
long received_count = 0;//接收计数
int n = serialPort1.BytesToRead;//先记录下来,避免某种原因,人为的原因,操作几次之间时间长,缓存不一致
byte[] buf = new byte[n];//声明一个临时数组存储当前来的串口数据
received_count = n;//增加接收计数
serialPort1.Read(buf, 0, n);//读取缓冲数据
builder.Clear();//清除字符串构造器的内容
myBy = buf;
myByLenth = buf.Length;
//因为要访问ui资源,所以需要使用invoke方式同步ui。
this.Invoke((EventHandler)(delegate
{
if (checkBox3.Checked)//接收时间显示
{
this.richTextBox1.AppendText(DateTime.Now.ToString(@"yyyy\:MM\:dd") " ");
this.richTextBox1.AppendText(DateTime.Now.ToString(@"HH\:mm\:ss\:fff") " ");
}
//判断是否是显示为16禁止
if (checkBox1.Checked)
{
//依次的拼接出16进制字符串
foreach (byte b in buf)
{
builder.Append(b.ToString("X2") " ");//在此实例的结尾追加指定字符串的副本
}
}
else
{
//直接按ASCII规则转换成字符串
builder.Append(Encoding.ASCII.GetString(buf));
}
//追加的形式添加到文本框末端,并滚动到最后。
this.richTextBox1.AppendText(builder.ToString());
myStr = builder.ToString();//字符串输出
if (checkBox2.Checked)//接收换行显示
{
this.richTextBox1.AppendText("\n");
}
//修改接收计数
//labelGetCount.Text = "Get:" received_count.ToString();
try
{
if (receiveDtatFlag == true)//保存数据
{
string fName = saveFileDialog1.FileName;
FileStream fs = File.Open(fName, FileMode.Append);
StreamWriter sw = new StreamWriter(fs);
if (checkBox3.Checked)//接收时间显示
{
//this.richTextBox1.AppendText(DateTime.Now.ToString() " ");
sw.Write(DateTime.Now.ToString(@"hh\:mm\:ss\:fff") " ");
}
sw.Write(builder.ToString());
if (checkBox2.Checked)//接收换行显示
{
sw.WriteLine("\n");
}
//sw.WriteLine(richTextBox1.Text);
//textBox3.Text = fName;
sw.Close();
fs.Close();
}
}
catch
{
}
//analysis myans = new analysis();
//myans.analysisData(myStr);
}));//*/
#endregion
}
private void richTextBox1_TextChanged(object sender, EventArgs e)//接收窗处理
{
if (richTextBox1.Lines.Length > 8000)//大于8000行时清楚前面的
{
int n = 500;
int start = richTextBox1.GetFirstCharIndexFromLine(0);//第一行第一个字符索引
int end = richTextBox1.GetFirstCharIndexFromLine(n);//第n行第一个字符索引
richTextBox1.Select(start, end);//选中n行
richTextBox1.SelectedText = "";//设置前n行为空
}
richTextBox1.Focus();
richTextBox1.Select(richTextBox1.TextLength, 0);
}
#endregion
#region 窗体处理
private void Form1_FormClosing(object sender, FormClosingEventArgs e)//关闭提醒
{
Properties.Settings.Default.Save();
myConfing.SetValue("COM", comboBox1.Text);
myConfing.SetValue("buadRate", comboBox2.Text);
myConfing.SetValue("Parity", comboBox3.Text);
myConfing.SetValue("dataBits", comboBox4.Text);
myConfing.SetValue("stopBits", comboBox5.Text);
if (DialogResult.Yes == MessageBox.Show("程序正在使用中,确认退出?", "确认退出", MessageBoxButtons.YesNo))
{
//MessageBox.Show("立即退出!");
serialPort1.Close();
this.Dispose();
e.Cancel = false;
}
else
{
e.Cancel = true;
}
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)//关闭整个窗口
{
Properties.Settings.Default.Save();
myConfing.SetValue("COM", comboBox1.Text);
myConfing.SetValue("buadRate", comboBox2.Text);
myConfing.SetValue("Parity", comboBox3.Text);
myConfing.SetValue("dataBits", comboBox4.Text);
myConfing.SetValue("stopBits", comboBox5.Text);
}
private void button3_Click(object sender, EventArgs e)//窗口隐藏
{
this.Hide();//隐藏窗体
}
#endregion
#region 数据文件保存处理
private void button4_Click(object sender, EventArgs e)//保存路径选择
{
//saveFileDialog1.InitialDirectory = @"G:\自制软件\C#练习\20.19 文件保存SaveFileDialog控件\51zxw";
saveFileDialog1.Filter = "文本文件(*.txt)|*.txt";
saveFileDialog1.FilterIndex = 1;
saveFileDialog1.FileName = "ReceiveData";
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
string fName = saveFileDialog1.FileName;
FileStream fs = File.Open(fName, FileMode.Append);
StreamWriter sw = new StreamWriter(fs);
//sw.WriteLine(richTextBox1.Text);
textBox3.Text = fName;
sw.Close();
fs.Close();
}
}
private void checkBox6_CheckedChanged(object sender, EventArgs e)//保存数据勾选处理
{
if (checkBox6.CheckState == CheckState.Checked)//选中
{
receiveDtatFlag = true;
}
else
{
receiveDtatFlag = false;
}
}
#endregion
#region 没有使用
public void portIDGet()//串口自动获取
{
try
{
comboBox1.Items.Clear();
foreach (string com in System.IO.Ports.SerialPort.GetPortNames())//串口检测
{
comboBox1.Items.Add(com);
}
//comboBox1.Text = myConfing.ConfingGetValue("COM");//使用配置文件加载
}
catch (Exception er)
{
MessageBox.Show("端口加载失败!" er.Message, "提示");
}
}
private void comboBox1_DragDrop(object sender, DragEventArgs e)
{
portIDGet();
}
private void comboBox1_DropDown(object sender, EventArgs e)
{
portIDGet();
}
#endregion
}
}
评论