2012-11-02 73 views
0

我想以編程方式在我的C#程序中設置串行(COM)端口設置(波特率,停止位等)。當我執行類似以下操作時,它不會將設置保存在我的Windows環境。我完全在錯誤的軌道上?在Windows環境中保存SerialPort設置

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(); 
+0

爲什麼要保存設置?你是否想過保存設置?如果你不想保存這些設置,而且它還是這樣做了呢? –

+0

您是否試圖在應用程序啓動之間保留設置或在運行時設置它們?您在此展示的任何內容都不會節省任何費用 –

+0

問題不明顯,請回復以前的評論提供更多信息。 –

回答

2

進入您的項目屬性的設置選項卡,併爲要堅持這樣的添加值的設置:

enter image description here

然後訪問它們在你的代碼是這樣的。在應用程序關閉時保存它們:

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 

    } 
}