首先添加Nuget包——System.IO.Port
安装完成后,添加using
使得ComboBox控件可以获取到下拉列表
打开xmal文件,添加 Loaded="Window_Loaded"
然后跳入到cs文件中,在Window_Loaded的方法中添加代码
string[] ports = SerialPort.GetPortNames();
this.Portname.ItemsSource = ports;
this.Portname.SelectedIndex = 1;
string[] baudrate = new string[] { "300", "600", "1200", "2400", "4800", "9600", "115200", "19200" };
this.Baudrate.ItemsSource = baudrate;
this.Baudrate.SelectedIndex = 6;
this.Databit.Items.Add(8);
this.Databit.Items.Add(7);
this.Databit.SelectedIndex = 0;
this.Stopbit.Items.Add(2);
this.Stopbit.Items.Add(1);
this.Stopbit.SelectedIndex = 0;
this.Parity.Items.Add("None");
this.Parity.Items.Add("Even");
this.Parity.Items.Add("Odd");
this.Parity.SelectedIndex = 0;
运行可以看到结果
此时,端口号中没有数据,我们可以下载一个软件来生成模拟端口号,软件链接放在文章末。
创建一个端口名称的类,方便其他文件引用。
右击项目名称
添加类,点击添加即可。
添加类
类设置为static,方便不用进行new就可以使用
public static SerialPort com { get; set; } = new SerialPort();
//串口名字
public static string com_name { get; set; }
//波特率
public static int com_Bound { get; set; }
//数据位
public static int com_DataBit { get; set; }
//校验位
public static string com_Verify { get; set; }
//停止位
public static string com_StopBit { get; set; }
//串口的打开状态标记位
public static bool OpenState { get; set; }
//数据显示
public static List<string> comdata = new List<string>();
链接:https://pan.baidu.com/s/1MLaEOoWOieIz_Il0eoWv_w
提取码:sgt1
软件使用方法文章:虚拟串口VSPD工具使用方法-CSDN博客