How to display the data read in DataReceived event handler of serialport(如何显示在串口的 DataReceived 事件处理程序中读取的数据)
问题描述
我有以下代码需要从端口读取数据,然后显示在文本框中.我为此目的使用 DataReceived 事件处理程序,但不知道如何在文本框中显示此数据.从各种来源我了解到 Invoke 方法应该用于此,但不知道如何使用它.请提出建议...
I have the following code which needs the data to be read from port and then display in a textbox. I am using DataReceived event handler for this purpose but donot know how to display this data in textbox. From various sources i learnt that Invoke method should be used for this but donot know how to use it. Suggestions please...
private void Form1_Load(object sender, EventArgs e)
{
//SerialPort mySerialPort = new SerialPort("COM3");
mySerialPort.PortName = "COM3";
mySerialPort.BaudRate = 9600;
mySerialPort.Parity = Parity.None;
mySerialPort.StopBits = StopBits.One;
mySerialPort.DataBits = 8;
mySerialPort.Handshake = Handshake.None;
mySerialPort.DataReceived += new SerialDataReceivedEventHandler(mySerialPort_DataReceived);
mySerialPort.Open();
}
private void mySerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
string s= sp.ReadExisting();
// next i want to display the data in s in a textbox. textbox1.text=s gives a cross thread exception
}
private void button1_Click(object sender, EventArgs e)
{
mySerialPort.WriteLine("AT+CMGL="ALL"");
}
推荐答案
MSDN 包含一个很好的文章 包含有关使用其他线程的控制方法和属性的示例.
The MSDN contains a good article with examples about using control methods and properties from other threads.
简而言之,您需要一个委托方法,该方法使用给定的字符串设置文本框的 Text 属性.然后,您通过 TextBox.Invoke() 方法从 mySerialPort_DataReceived 处理程序中调用该委托.像这样的:
In short, what you need is a delegate method that sets the Text property of your text box with a given string. You then call that delegate from within your mySerialPort_DataReceived handler via the TextBox.Invoke() method. Something like this:
public delegate void AddDataDelegate(String myString);
public AddDataDelegate myDelegate;
private void Form1_Load(object sender, EventArgs e)
{
//...
this.myDelegate = new AddDataDelegate(AddDataMethod);
}
public void AddDataMethod(String myString)
{
textbox1.AppendText(myString);
}
private void mySerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
string s= sp.ReadExisting();
textbox1.Invoke(this.myDelegate, new Object[] {s});
}
这篇关于如何显示在串口的 DataReceived 事件处理程序中读取的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何显示在串口的 DataReceived 事件处理程序中读取的数据
基础教程推荐
- C# 从 List<List<int>> 中删除重 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- WPF 模态进度窗口 2022-01-01
