我能够通过串口接收数据,但我想在richtextbox中看到它。 [英] I am able to receive the data through serial port but I want to see it in richtextbox.

查看:109
本文介绍了我能够通过串口接收数据,但我想在richtextbox中看到它。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想看到收到的数据进入richTextbox但是我得到一个例外,不允许交叉线程。请任何人都可以给我那个小代码。我是线程新手。



我尝试了什么:



我遇到交叉线程异常。

I want to see the received data into the richTextbox but i am getting an exception that,cross thread is not allowed.Please can anyone give me that small code.I am new to threading.

What I have tried:

I am getting cross threading exception.

推荐答案





这是一个古老的常见问题。您所看到的是来自串行端口的数据正在另一个线程上接收。运行Windows UI的线程是不同的。这就像在同一栋房子里运行的两台不同的机器,但是一个人不知道如何处理另一台机器。



所以你需要所谓的代表。



请参阅下面的代码。





Hi,

This is an old and commonly asked question. What you are seeing is that your data from the serial port is being received on another thread. The thread that is running the Windows UI is different. It's like two different machines running in the same house, but one has no idea how to deal with the other.

So you need what's called a delegate.

See the code below.


// I've named this 'StringDelegate' - returns void and carries a string.
delegate void StringDelegate(string text); 


// Look at your rich text box, use the rich text box control's 
// name property in place where I have written 'richTextBox1'


//
// Call this method directly with the 
// data from your Serial port.
//
private void SetText(string text)  
{  
    // InvokeRequired required compares the thread ID of the  
    // calling thread to the thread ID of the creating thread.  
    // If these threads are different, it returns true.  
    if (this.richTextBox1.InvokeRequired)  
    {     

        StringArgReturningVoidDelegate d = new StringArgReturningVoidDelegate(SetText);  
        this.Invoke(d, new object[] { text });  
    }  
    else  
    {  
        this.richTextBox1.Text = text;  
    }  
}  


这篇关于我能够通过串口接收数据,但我想在richtextbox中看到它。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆