开发者

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:

Why the Weird Spacing in RichTextBox

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, SerialDataReceivedE开发者_C百科ventArgs 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.


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...


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜