简体   繁体   English

从串口读取时裁剪的C#richtextbox数据

[英]C# richtextbox data clipped while reading from serial port

I am writing a C# program which could continuously take data from the serial port and immediately display it on the rich text box of WPF. 我正在编写一个C#程序,该程序可以连续从串行端口获取数据,并立即将其显示在WPF的富文本框中。 The problem is that when I use the below code, the first bit of every HEX value is clipped and I get an output like (Say) 问题是,当我使用以下代码时,每个十六进制值的第一位都被裁剪,并且得到类似(说)的输出

B 3C 3F 3F 3F 3F 3F 3F 3F 3F 3F 3F 3F 3F 3F 3F 3F 3F 3F 3F 3F 3F 3F 3F 3F 3F 3F 3F 3F 3F 3F 3F 3F 3F 

Instead of getting 而不是得到

0B 3C FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF.

Why is this happening and what mistake I am making? 为什么会发生这种情况?我正在犯什么错误? I have checked with Terminal software and the data that I am receiving is correct. 我已经用终端软件检查过,并且我收到的数据是正确的。 It is only while displaying in my program where it clips the first bit. 只有在我的程序中显示时,它才会剪切第一位。

Also how do I separate the first 2 and the last 2 bytes and stop it from being displayed on the richtextbox. 另外,我如何分隔前2个字节和后2个字节,并阻止它在Richtextbox上显示。 The code is below: 代码如下:

 string received_data = serialPort1.ReadExisting();
char[] store_char_array = received_data.ToCharArray();
string display_text = "" ;
foreach (var i in store_char_array)
      {
         string hex_value = String.Format("{0:X}", Convert.ToUInt32(i));
  display_text += hex_value + " ";

 }

Invoke(new Action(() => richTextBox1.AppendText(display_text)));

Thanks in advance 提前致谢

It is a problem with encoding. 这是编码问题。 You have to add this when you configure your serial port: 配置串行端口时,必须添加以下内容:

SerialPort.Encoding = System.Text.Encoding.GetEncoding(28591) SerialPort.Encoding = System.Text.Encoding.GetEncoding(28591)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM