听取串口。如何将字符串添加到列表框?

时间:2012-03-08 22:01:14

标签: c# winforms serial-port

我有一个问题。我尝试听串口(COM20),然后我收到数据,我想在申请表上将这些数据添加到ListBox1。我需要为它添加什么代码? 我知道INVOKE,但我不明白我必须如何使用它。请帮帮我。

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;

namespace test_com_port
{
    public partial class Form1 : Form
    {


        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            SerialPort mySerialPort = new SerialPort("COM20");
            mySerialPort.BaudRate = 9600;
            mySerialPort.Parity = Parity.None;
            mySerialPort.StopBits = StopBits.One;
            mySerialPort.DataBits = 8;
            mySerialPort.Handshake = Handshake.None;



            mySerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
            mySerialPort.Open();

        }
        private static void DataReceivedHandler(object sender,SerialDataReceivedEventArgs e)
        {
          SerialPort sp = (SerialPort)sender;
                string indata = sp.ReadExisting();


        char[] values = indata.ToCharArray();
        foreach (char letter in values)
        {

            int value = Convert.ToInt32(letter);
            string hexOutput = String.Format("{0:X}", value);
            listBox1.Items.Add(hexOutput);


        }  

        }

    }


    }

1 个答案:

答案 0 :(得分:4)

只需添加添加事件处理程序的顶部:

if (InvokeRequired)
 BeginInvoke(new SerialDataReceivedEventHandler(DataReceivedHandler), sender, e);