using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
class my_SerialPort
{
//
SerialPort port;
ToolStripComboBox comboBox_com;
ToolStripComboBox comboBox_bot;
ToolStripButton button;
//
byte[] byte_data = new byte[5000];
UInt16 byte_length;
//
public bool flag = false;
//
public void into_control(ToolStripComboBox _comboBox_com,
ToolStripComboBox _comboBox_bot,
ToolStripButton _button,
SerialPort _port)
{
button = _button;
comboBox_bot = _comboBox_bot;
comboBox_com = _comboBox_com;
port = _port;
//
comboBox_bot.Items.Add("9600");
comboBox_bot.Items.Add("19200");
comboBox_bot.Items.Add("56000");
comboBox_bot.Items.Add("115200");
comboBox_bot.Text = "9600";
//
comboBox_com.Text = "COM1";
//
button.Click += button_Click;
comboBox_com.DropDown += comboBox_com_DropDown;
port.DataReceived += serialPort1_DataReceived;
//
}
//开关串口
private void button_Click(object sender, EventArgs e)
{
if (port.IsOpen)
#region
{
try
{
port.Close();
button.Text = "打开串口";
button.ForeColor = Color.Red;
comboBox_com.Enabled = true;
comboBox_bot.Enabled = true;
//timer1.Stop();
}
catch
{
MessageBox.Show("串口关闭失败", "错误");
}
}
#endregion
else
#region
{
try
{
port.PortName = comboBox_com.Text;//端口号
port.BaudRate = Convert.ToInt32(comboBox_bot.Text);
port.Open();//打开端口
button.Text = "关闭串口";
button.ForeColor = Color.Green;
// timer1.Start();
comboBox_com.Enabled = false;
comboBox_bot.Enabled = false;
}
catch
{
MessageBox.Show("串口打开失败", "错误");
}
}
#endregion
}
//下拉框选择可用串口号
private void comboBox_com_DropDown(object sender, EventArgs e)
{
comboBox_com.Items.Clear();
string[] sps = SerialPort.GetPortNames();
comboBox_com.Items.AddRange(sps);
}
//串口接收事件
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
System.Threading.Thread.Sleep(100);
byte[] R_buffer = new byte[port.BytesToRead];
UInt16 length = Convert.ToUInt16(port.Read(R_buffer, 0, port.BytesToRead));
//
R_buffer.CopyTo(byte_data, 0);
byte_length = length;
flag = true;
}
//
public SerialPort get_port()
{
return port;
}
//
public void get_data(ref byte[] bytes, ref UInt16 length)
{
length = byte_length;
for (UInt16 i = 0; i < length; i++)
{
bytes[i] = byte_data[i];
}
flag = false;
}
}
}
C# winform 串口 类 封装
最新推荐文章于 2023-12-06 10:28:49 发布