gpt4 book ai didi

c# - 从蓝牙接收字符串后使用线程更新标签

转载 作者:太空狗 更新时间:2023-10-30 00:58:14 25 4
gpt4 key购买 nike

大家好,我有一个线程能够读取从蓝牙流接收的数据。在发件人部分,我做了一个 while 循环,其中计数不断增加 + 1。我做了一个 messagebox.show(test);它工作正常但是当我做一个 label.text = test 我得到:

“Control.Invoke 必须用于与在单独线程上创建的控件进行交互。”错误。我在 C# 中的后续代码:

Thread t = new Thread(new ThreadStart(readStream)); t.开始(); 公共(public)无效 readStream() { 而(真) { String test = manager.Reader.ReadLine(); label1.Text = 测试; }

我的问题是,如何更新线程中的标签?有什么简单的控制调用方法吗?

最佳答案

你好,这是一个如何做到这一点的例子:

http://msdn.microsoft.com/en-us/library/ms171728.aspx

如果您想从另一个线程更新标签,您应该使用与此类似的函数。您不能直接更新它。

简而言之:你应该这样写:

delegate void SetTextCallback(string text);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.textBox1.InvokeRequired)  {     SetTextCallback d = new SetTextCallback(SetText);    this.Invoke(d, new object[] { text });  }  else  {    this.textBox1.Text = text;  }}

关于c# - 从蓝牙接收字符串后使用线程更新标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3226782/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com