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);
}
}
}
}
答案 0 :(得分:4)
只需添加添加事件处理程序的顶部:
if (InvokeRequired)
BeginInvoke(new SerialDataReceivedEventHandler(DataReceivedHandler), sender, e);