本文介绍了在标签上显示串口数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
谁能帮助我,读取标签上的串行端口数据? 我可以读取串行端口数据,但无法在标签中显示它:
Who can help me about, read serial port data on label? I can read serial port data, but i can not show it in the label:
private void DataRecievePort_DataReceived(object sender, SerialDataReceivedEventArgs e) { byte[] data = new byte[DataRecievePort.BytesToRead]; DataRecievePort.Read(data, 0, data.Length); ASCIIEncoding enc = new ASCIIEncoding(); double Pu = Convert.ToInt32(enc.GetString(data)); double Me = (Pu * 2); label1.Text = Convert.ToString(me); //This line gives error }推荐答案
我猜想是因为.NET中存在交叉线程 该代码将解决您的问题. 这是sln链接: imljh.ucoz/code/test_serialport_label.zip I guess that because crossing thread in .NET this code will solve your problem. this is the sln link: imljh.ucoz/code/test_serialport_label.zip 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; using System.Threading; namespace test_serialport_label { public partial class Form1 : Form { Thread t1; delegate void write_txt(string msg1); write_txt wr; public Form1() { InitializeComponent(); t1 = new Thread(new ParameterizedThreadStart(drawer_intz)); wr = new write_txt(drawer); } private void DataRecievePort_DataReceived(object sender, SerialDataReceivedEventArgs e) { byte[] data = new byte[DataRecievePort.BytesToRead]; DataRecievePort.Read(data, 0, data.Length); ASCIIEncoding enc = new ASCIIEncoding(); double Pu = Convert.ToInt32(enc.GetString(data)); double Me = (Pu * 2); if (t1.IsAlive) t1.Abort(); t1.Start(Convert.ToString(Me)); } private void drawer_intz(object obj) { string Me2 = (string)obj; this.Invoke(wr, Me2); } private void drawer(string txt) { label1.Text = txt; label1.Refresh(); } private void Form1_FormClosing(object sender, FormClosingEventArgs e) { if (t1 != null) t1.Abort(); } } }
更多推荐
在标签上显示串口数据
发布评论