0

我想在我的 C# 程序中以编程方式设置串行 (COM) 端口设置(波特率、停止位等)。当我执行以下操作时,它不会将设置保存在我的 Windows 环境中。我完全走错了吗?

  SerialPort serialPort = new SerialPort();
  string[] ports = SerialPort.GetPortNames();

  serialPort.PortName = "COM5";
  serialPort.BaudRate = 9600;
  serialPort.DataBits = 8;
  serialPort.DtrEnable = true;

  serialPort.StopBits = StopBits.One;
  serialPort.Parity = Parity.None;
  if (serialPort.IsOpen) serialPort.Close();
4

1 回答 1

2

进入您的项目属性的设置选项卡并添加您想要保留的值的设置,如下所示:

在此处输入图像描述

然后像这样在您的代码中访问它们。当您的应用程序关闭时保存它们:

public partial class Form1 : Form
{
    SerialPort serialPort; 
    public Form1()
    {
        InitializeComponent();
        serialPort = new SerialPort();
        serialPort.PortName = Properties.Settings.Default.PortName;
        serialPort.BaudRate = Properties.Settings.Default.BaudRate;
        serialPort.DataBits = Properties.Settings.Default.DataBits;
        serialPort.DtrEnable = Properties.Settings.Default.DtrEnable;
        serialPort.StopBits = Properties.Settings.Default.StopBits;
        serialPort.Parity = Properties.Settings.Default.Parity;

    }

    private void button1_Click(object sender, EventArgs e)
    {
        serialPort.PortName = "COM1";
    }

    private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        Properties.Settings.Default.PortName = serialPort.PortName;
        Properties.Settings.Default.BaudRate = serialPort.BaudRate;
        Properties.Settings.Default.DataBits = serialPort.DataBits;
        Properties.Settings.Default.DtrEnable = serialPort.DtrEnable;
        Properties.Settings.Default.StopBits = serialPort.StopBits;
        Properties.Settings.Default.Parity = serialPort.Parity;
        Properties.Settings.Default.Save(); //Saves settings 

    }
}
于 2012-11-03T00:09:39.823 回答