串口扫码枪读取主要代码段
1 public partial class Form1 : Form 2 { 3 public Form1() 4 { 5 InitializeComponent(); 6 } 7 SerialPort sp = new SerialPort("COM1", 115200, Parity.None, 8, StopBits.One); 8 9 delegate void UpdateTextEventHandler(string text); 10 UpdateTextEventHandler updateText; 11 12 private void Form1_Load(object sender, System.EventArgs e) 13 { 14 try 15 { 16 if (sp.IsOpen) 17 { 18 sp.Close(); 19 } 20 sp.Open(); 21 toolStripStatusLabel3.Text += "Ready"; 22 toolStripStatusLabel3.ForeColor = System.Drawing.Color.Green; 23 } 24 catch (Exception) 25 { 26 toolStripStatusLabel3.Text += "COM1打開失敗"; 27 toolStripStatusLabel3.ForeColor = System.Drawing.Color.Red; 28 } 29 30 31 updateText += new UpdateTextEventHandler(UpdateTextBox); 32 sp.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived); 33 } 34 35 36 private void UpdateTextBox(string text) 37 { 38 listBox1.Items.Add(text); 39 } 40 41 private void sp_DataReceived(object sender, SerialDataReceivedEventArgs e) 42 { 43 Thread.Sleep(100); 44 45 string readString = sp.ReadExisting(); 46 this.Invoke(updateText, new string[] { readString }); 47 } 48 }