軟體平台:C# + WINCE6.0
硬體平台:tiny6410
[csharp]
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using System.Threading;
namespace test_serialport
{
public partial class Form1 : Form
{
// 接收用緩衝
Byte[] recv_bytes;
public Form1()
{
InitializeComponent();
// 開啟串口
serialPort1.Open();
// 註冊接收事件
serialPort1.DataReceived += recv_udp_func;
}
// 發送按鈕
private void button1_Click(object sender, EventArgs e)
{
serialPort1.Write(textBox1.Text);
}
// 接收事件
void recv_udp_func(object sender, SerialDataReceivedEventArgs e)
{
// 取得緩衝區中的位元組數
int n = serialPort1.BytesToRead;
// 建立臨時陣列存放這次收到的資料
byte[] buf = new byte[n];
serialPort1.Read(buf, 0, n); // 讀出緩衝資料
// 透過 Invoke 回到主線程更新介面
this.Invoke((EventHandler)delegate {
this.textBox2.Text = Encoding.Default.GetString(buf, 0, n);
});
}
}
}
相較於自己開 thread 輪詢,直接用 DataReceived 事件更省事:資料一到,.NET 就會呼叫你註冊的處理常式。只要記得所有跨執行緒的控件更新都包在 Invoke 裡,就不會出現非同步執行的例外。