博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[转]How to display the data read in DataReceived event handler of serialport
阅读量:6074 次
发布时间:2019-06-20

本文共 2086 字,大约阅读时间需要 6 分钟。

本文转自:

 

问:

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\"");    } 答:

The MSDN contains a good  with examples about using control methods and properties from other threads.

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});       }

转载地址:http://xaxgx.baihongyu.com/

你可能感兴趣的文章
函数是对象-有属性有方法
查看>>
uva 10107 - What is the Median?
查看>>
Linux下基本栈溢出攻击【转】
查看>>
c# 连等算式都在做什么
查看>>
使用c:forEach 控制5个换行
查看>>
java web轻量级开发面试教程摘录,java web面试技巧汇总,如何准备Spring MVC方面的面试...
查看>>
使用ansible工具部署ceph
查看>>
linux系列博文---->深入理解linux启动运行原理(一)
查看>>
Android反编译(一) 之反编译JAVA源码
查看>>
结合当前公司发展情况,技术团队情况,设计一个适合的技术团队绩效考核机制...
查看>>
python-45: opener 的使用
查看>>
cad图纸转换完成的pdf格式模糊应该如何操作?
查看>>
Struts2与Struts1区别
查看>>
网站内容禁止复制解决办法
查看>>
Qt多线程
查看>>
我的友情链接
查看>>
想说一点东西。。。。
查看>>
css知多少(8)——float上篇
查看>>
NLB网路负载均衡管理器详解
查看>>
水平添加滚动条
查看>>