日期:2014-05-17 浏览次数:21033 次
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
// public System.IO.Ports.SerialPort com = new System.IO.Ports.SerialPort();
private void button1_Click(object sender, EventArgs e)
{
serialPort1.PortName = "COM4";
serialPort1.Open();
}
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
// 获取字节长度
int bytes = serialPort1.BytesToRead;
// 创建字节数组
byte[] buffer = new byte[bytes];
// 读取缓冲区的数据到数组
serialPort1.Read(buffer, 0, bytes);
// 显示读取的数据到数据窗口
[color=#FF0000]this.BeginInvoke[/color](new TextBoxValueAssignDelegate(this.AssignTextBoxValue), new object[] { textBox1, byteToHexStr(buffer) + "\n" });
}
public string byteToHexStr(byte[] bytes)
{
string returnStr = "";
if (bytes != null)
{
for (int i = 0; i < bytes.Length; i++)
{
returnStr += bytes[i].ToString("X2");
returnStr += " ";
}
}
return returnStr;
}
private void AssignTextBoxValue(TextBox textBox1, string textBoxValue)
{
textBox1.Text += textBoxValue;
}
private delegate void TextBoxValueAssignDelegate(TextBox textBox1, string textBoxValue);
[color=#FF0000]private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
serialPort1.Close();
}[/color]
}