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; private delegate void setTextDeleg(string text); public delegate void myDelegate(); SerialPort serialPort = new SerialPort(); private void Form1_Load(object sender, EventArgs e) { string[] portname = SerialPort.GetPortNames(); foreach (string name in portname) comboBox1.Items.Add(name); } private void button1_Click(object sender, EventArgs e) { if (this.comboBox1.SelectedIndex == -1) { MessageBox.Show("Please select comm port first!"); } else if (serialPort.IsOpen) serialPort.Close(); try { { serialPort.PortName = comboBox1.Text; serialPort.BaudRate = 9600; serialPort.Parity = Parity.None; serialPort.DataBits = 8; serialPort.StopBits = StopBits.One; serialPort.Encoding = System.Text.Encoding.ASCII ; } serialPort.Open(); label1.Text = comboBox1.Text + " is opened"; // textBox1.Text = serialPort.DataReceived += new SerialDataReceivedEventHandler(datareceived); } catch (Exception ex) { MessageBox.Show(ex.Message.ToString()); } } void datareceived(object sender, SerialDataReceivedEventArgs e) { myDelegate d = new myDelegate(update); textBox1.Invoke(d, new object[] { }); } public void update() { textBox1.AppendText(serialPort.ReadExisting()); textBox1.ScrollToCaret(); } } }
var
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)