一、關於DataReceive事件。
主程序必須有
outserialPort.DataReceived +=new SerialDataReceivedEventHandler(outserialPort_DataReceived);//注冊received事件
創建 SerialDataReceivedEventHandler 委托即把接受數據的時間關聯到相應的事件去。否則接收事件發生時無法觸發對應的方法。
+=表示增加注冊一種方法,而-=則相反。
二、讀取串口數據的兩種方法
第一種是采用read方法讀取
int n = outserialPort.BytesToRead;
byte[] buf = new byte[n];
outserialPort.Read(buf, 0, n);
string receivedata = System.Text.Encoding.ASCII.GetString(buf);
第二種是采用readline方法讀取
string receivedata = outserialPort.ReadLine();
注意:
1、ReadLine()方法一直會讀到有一個新的行才會返回,所以如果發送數據中沒有換行符則該方法不會返回,會一直停留在readline程序里不會執行之后的程序,而read()是調用者自己定義一個byte數組來接收串口中緩存里的數據,byte多長就讀多長
參考:http://bbs.csdn.net/topics/330233058
2、 string receivedata=System.Text.Encoding.ASCII.GetString(buf);
注意串口接收的編碼是ASCII型而不是Unicode否則無法讀出接收的數據
三、Invoke的兩種書寫方法:
第一種
this.Invoke(new EventHandler(delegate
{
//要委托的代碼
}));
第二種
delegate void mydelegate(object sender, System.EventArgs e);
mydelegate interfaceUpdateHandle;
然后再在主線程中
interfaceUpdateHandle = new mydelegate(button1_Click); //實例化委托對象
在附屬線程中則
this.Invoke(interfaceUpdateHandle, null, null);
其中,invoke的參數數量應該要和聲明的時候一致即和delegate后的函數參數數量一致。而且mydelegate這個名稱可以自取。
四、如何知道當前電腦有哪個串口
方法1:comboBox1.Items.AddRange(System.IO.Ports.SerialPort.GetPortNames());
方法2:string[] portList = System.IO.Ports.SerialPort.GetPortNames();
for (int i = 0; i < portList.Length; ++i)
{
string name = portList[i];
comboBox1.Items.Add(name);
}
參考:http://blog.csdn.net/cy757/article/details/4474930
五、參考資料:
1、C#串口操作系列教程:http://blog.csdn.net/wuyazhe/article/category/695097
2、C# SerialPort運行方式:(關於如何讀取接收數據)http://www.cnblogs.com/lzjsky/archive/2011/04/07/2008089.html