private void button1_Click(object sender, EventArgs e) { SerialPort mySerialPort = new SerialPort("COM1"); mySerialPort.BaudRate = 9600; mySerialPort.Parity = Parity.None; mySerialPort.StopBits = StopBits.One; mySerialPort.DataBits = 8; mySerialPort.Handshake = Handshake.None; mySerialPort.RtsEnable = true; SerialPort sp = (SerialPort)sender; label1.Text = sp.ReadExisting(); mySerialPort.Open(); mySerialPort.Close(); }
public partial class MainForm : Form { SerialPortManager _spManager; public MainForm() { InitializeComponent(); DoubleBuffered = true; UserInitialization(); } private void UserInitialization() { _spManager = new SerialPortManager(); SerialSettings mySerialSettings = _spManager.CurrentSerialSettings; serialSettingsBindingSource.DataSource = mySerialSettings; portNameComboBox.DataSource = mySerialSettings.PortNameCollection; baudRateComboBox.DataSource = mySerialSettings.BaudRateCollection; dataBitsComboBox.DataSource = mySerialSettings.DataBitsCollection; parityComboBox.DataSource = Enum.GetValues(typeof(System.IO.Ports.Parity)); stopBitsComboBox.DataSource = Enum.GetValues(typeof(System.IO.Ports.StopBits)); _spManager.NewSerialDataRecieved += new EventHandler<SerialDataEventArgs>(_spManager_NewSerialDataRecieved); this.FormClosing += new FormClosingEventHandler(MainForm_FormClosing); } private void MainForm_FormClosing(object sender, FormClosingEventArgs e) { _spManager.Dispose(); } void _spManager_NewSerialDataRecieved(object sender, SerialDataEventArgs e) { if (this.InvokeRequired) { this.BeginInvoke(new EventHandler<SerialDataEventArgs>(_spManager_NewSerialDataRecieved), new object[] { sender, e }); return; } int maxTextLength = 1000; // maximum text length in text box if (tbData.TextLength > maxTextLength) tbData.Text = tbData.Text.Remove(0, tbData.TextLength - maxTextLength); string str = Encoding.ASCII.GetString(e.Data); tbData.AppendText(str); tbData.ScrollToCaret(); DoubleBuffered = true; label1.Text = str; } private void btnStart_Click(object sender, EventArgs e) { _spManager.StartListening(); } private void btnStop_Click(object sender, EventArgs e) { _spManager.StopListening(); } }
var
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)