using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Serilport
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void SearchAndAddSerialToComboBox(object sender, EventArgs e)
{
string Buffer;
comboBox1.Items.Clear(); //清初之前已经扫描的记录
for (int i = 0; i < 20; i++)
{
try
{
Buffer = "COM" + i.ToString(); //获得COM1-20
serialPort1.PortName = Buffer; //获取COM信息
serialPort1.Open(); //打开串口
comboBox1.Items.Add(Buffer);
comboBox1.Text = Buffer; //添加串口得到记录集
serialPort1.Close(); //关闭串口
}
catch { }
}
}
private void button4_Click(object sender, EventArgs e)
{
try
{
serialPort1.PortName = comboBox1.Text;
serialPort1.BaudRate = Convert.ToInt32(comboBox2.Text, 10);
serialPort1.DataBits = Convert.ToInt32(comboBox3.Text, 10);
if (comboBox4.Text == "None") { serialPort1.Parity = Parity.None; }
else if (comboBox4.Text == "奇校验") { serialPort1.Parity = Parity.Odd; }
else if (comboBox4.Text == "偶校验") { serialPort1.Parity = Parity.Even; }
else if (comboBox4.Text == "Mark") { serialPort1.Parity = Parity.Mark; }
else if (comboBox4.Text == "空格校验") { serialPort1.Parity = Parity.Space; }
if (comboBox5.Text == "1")
{
serialPort1.StopBits = StopBits.One;
}
else if (comboBox5.Text == "1.5")
{
serialPort1.StopBits = StopBits.OnePointFive;
}
else if (comboBox5.Text == "1.5")
{
serialPort1.StopBits = StopBits.Two;
}
//serialPort1.ReadTimeout(2000);
serialPort1.Open();
button2.Enabled = false;//打开串口按钮不可用
//button3.Enabled = true;//关闭串口
}
catch
{
MessageBox.Show("端口错误,请检查串口", "错误");
}
}
}
}
评论