简体   繁体   中英

Why the Weird Spacing in RichTextBox

I am receiving input via a serial port and displaying the data in a RichTextBox. That works okay, except for the fact that, when I display the data, there is a lot of extra (non-consistently occurring) spacing. See the image below:

在此处输入图片说明

In this case, it is showing every two ticks, but sometimes it is three or sometimes none. I can't figure out why this is. Does anybody have any idea?

Edit : Here is how I am displaying the data (code-wise).

void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
  string msg = port.ReadExisting();
  DisplayWindow.AppendText(msg);
  DisplayWindow.ScrollToCaret();
}

Looks like SerialPort.NewLine to me, a linefeed by default ('\\n'). Also check that you actually got something from the port and didn't just append an empty line to the RTB.

Troubleshooting code from a screenshot just doesn't work really well. Use the debugger.

Even better, use a TextBox with MultiLine set to true rather than a RichTextBox . The TextBox ignores the \\r character in the data and gives a new line whenever it sees the \\n character.

Here is some sample code:

  private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
  {
     String ser_data = this.serialPort1.ReadExisting();
  }

...later in callback function:

richtextbox.AppendText(ser_data);

Put a breakpoint just past the line to read the data. Then send carriage returns via HyperTerminal from the other computer. You will notice that sometimes the data received is \\r\\n. This gives you a single return as you expect. However, sometimes the \\r is received separate from the \\n. In this case you get an extra linefeed in the rich text box. Either buffer up the data so the rich text box gets the \\r\\n together, remove one of them from the string, or strip one (\\r or \\n) off from the source computer. For example, in HyperTerminal go to File->Properties->Settings->ASCII Setup and uncheck "Send line ends with line feeds".

I know the original poster is done with this discussion. But if you're reading this, I hope it helps you.

Thank you Hans and ChrisF for your responses. As I was working on this, I decided to search on ReadExisting(). Through some SO posts, it turns out that this might have been my problem. I changed it to ReadLine() and I'm not getting the weird line breaks anymore. I'm going to continue using this method and see if it works with the rest of my application.

Very strange...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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