I do not know why but it always enters two new lines:
private void getMyIPAddress()
{
String Address = "";
this.Dispatcher.Invoke(() =>
{
this.RichTextBox_logs.VerticalScrollBarVisibility = ScrollBarVisibility.Visible;
});
while (true)
{
this.Dispatcher.Invoke(() =>
{
this.RichTextBox_logs.AppendText(Environment.NewLine);
//this.RichTextBox_logs.ScrollToEnd();
});
WebRequest request = WebRequest.Create("http://checkip.dyndns.com/");
try
{
using (WebResponse response = request.GetResponse())
{
using (StreamReader stream = new StreamReader(response.GetResponseStream()))
{
Address = stream.ReadToEnd();
}
int first = Address.IndexOf("Address: ") 9;
int last = Address.IndexOf("</body>");
if (CurrentAddressHolder != Address.Substring(first, last - first))
{
CurrentAddressHolder = Address.Substring(first, last - first);
this.Dispatcher.Invoke(() =>
{
this.textBox_ip.Text = CurrentAddressHolder;
});
}
this.Dispatcher.Invoke(() =>
{
this.RichTextBox_logs.AppendText("IP is " CurrentAddressHolder);
});
}
}
catch(Exception e)
{
this.Dispatcher.Invoke(() =>
{
this.RichTextBox_logs.AppendText(e.ToString());
});
}
}
}
I'm new to multi-threading and I'm not sure if it affected the syntax to the new line.
Any inputs or code revisions/improvements are highly welcomed. Thanks.
CodePudding user response:
Seems like your problem is line spacing.
Solution one:
Instead of the AppendText()
method use the following method to add a text line to the RichTextBox
:
public void AddText(RichTextBox rtb, string message, double spacing = 4)
{
var paragraph = new Paragraph() { LineHeight = spacing };
paragraph.Inlines.Add(new Run(message));
rtb.Document.Blocks.Add(paragraph);
}
With this method you will able to change line spacing between paragraphs programmatically by setting the LineHeight value.
When using this approach don't necessary to add the Environment.NewLine
. Each block (paragraph) will automatically formatted as different line.
Solution two:
Try to change the paragraph margin (see the following post https://stackoverflow.com/a/445897/6630084):
<RichTextBox x:Name="RichTextBox_logs" >
<RichTextBox.Resources>
<Style TargetType="{x:Type Paragraph}">
<Setter Property="Margin" Value="0"/>
</Style>
</RichTextBox.Resources>
...
<RichTextBox>