功能展示:
代码:
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;
using System.IO;
using System.Text.RegularExpressions;
namespace chuankou5
{
public partial class Form1 : Form
{
string data;
private string[] portNames = null;
private object[] baudRates = { 4800, 9600, 19200 };
private static string[] dataBuff=new string[1000];
private bool Ready = false;
private bool contrl = false;
private static int getData_Num = 0;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
portNames = SerialPort.GetPortNames();
this.portNumberComboBox1.Items.AddRange(this.portNames);
this.baudRatecomboBox.Items.AddRange(baudRates);
}
//发送数据
private void button1_Click(object sender, EventArgs e)
{
//如果contrl未false,串口没有打开
if(contrl==false)
{
int baurate = 9600;
string port = portNumberComboBox1.Text;
string baurate_str = baudRatecomboBox.Text.Trim();
if (port != "")
{
serialPort1.PortName = port;
if (baurate_str != "")
{
int baurate_int = Convert.ToInt16(baurate_str) + 1;
baurate = baurate_int - 1;
serialPort1.BaudRate = baurate;
Ready = true;
openButton.Text = "关闭串口";
contrl = true;
}
}
else
{
MessageBox.Show("请选择要打开的串口号!", "提示");
}
}
else
{
Ready = false;
openButton.Text = "打开串口";
contrl = false;
}
OpenPort();
}
private void OpenPort()
{
//如果准备好,将则将端口打开
if (Ready==true)
{
try
{
serialPort1.Open();
}
catch(Exception ex)
{
MessageBox.Show("串行端口打开失败!具体原因:" + ex.Message, "提示信息");
}
}
else
{
serialPort1.Close();
}
}
private void button2_Click(object sender, EventArgs e)
{
serialPort1.Close();
Close();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (serialPort1.IsOpen) serialPort1.Close();
}
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
data = serialPort1.ReadExisting();
int buffData_num = dataBuff.Length;
dataBuff[getData_Num] = data;
this.Invoke(new EventHandler(DisplayText));
getData_Num = getData_Num + 1;
}
//显示数据
private void DisplayText(object sender,EventArgs e)
{
//char[] data1 = data.ToCharArray();//字符串转成字符数组
//short data2 = (short)data1[0];
textBox2.Text = textBox2.Text + data;
}
private void label2_Click(object sender, EventArgs e)
{
}
private void setDataButton_Click_1(object sender, EventArgs e)
{
string outdata = this.textBox1.Text;
if (outdata == "")
{
MessageBox.Show("发送的数据不能为空!");
}
else
{
serialPort1.Write(outdata);
}
}
}
}