日期:2014-05-18 浏览次数:21139 次
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO.Ports; namespace Demo { public partial class myForm : Form { //private int[] ReceiveData = new int[4]; //private int ReceiveDataIndex = 0; string ReceiveData; public myForm() { InitializeComponent(); } private void myForm_Load(object sender, EventArgs e) { comboBoxPortName.SelectedIndex = 0; comboBoxBaudRate.SelectedIndex = 5; comboBoxParity.SelectedIndex = 0; comboBoxDataBits.SelectedIndex = 0; comboBoxStopBits.SelectedIndex = 0; btnClose.Enabled = false; btnOpen.Enabled = true; textBoxInformation.Text = "系统初始化成功!\r\n"; } private void btnOpen_Click(object sender, EventArgs e) { String myParity; String myStopBits; myParity = comboBoxParity.SelectedItem.ToString(); myStopBits = comboBoxStopBits.SelectedItem.ToString(); //设置端口号 mySerialPort.PortName = comboBoxPortName.SelectedItem.ToString(); //设置波特率 mySerialPort.BaudRate = Convert.ToInt32(comboBoxBaudRate.SelectedItem); //设置校验位 switch (myParity) { case "None": mySerialPort.Parity = Parity.None; break; case "Even": mySerialPort.Parity = Parity.Even; break; case "Odd": mySerialPort.Parity = Parity.Odd; break; default: mySerialPort.Parity = Parity.None; break; } //设置数据位 mySerialPort.DataBits = Convert.ToInt32(comboBoxDataBits.SelectedItem); //设置停止位 switch(myStopBits) { case "1": mySerialPort.StopBits = StopBits.One; break; case "2": mySerialPort.StopBits = StopBits.Two; break; default: mySerialPort.StopBits = StopBits.One; break; } //采用ASCII编码方式 mySerialPort.Encoding = Encoding.ASCII; //接收到一个字符就出发接收事件