日期:2014-05-17  浏览次数:20862 次

c#用serialport读数据就死啊,怎么办
c#用serialport读数据就死啊,怎么办!
不读数据是正常关闭,只要读数就程序就死掉啊,那个帮忙解决下!!!!!!!!!!!!

------解决方案--------------------
C# code

    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]
    }