How do I set the Richtextbox.rtf to a rich text string? - vb.net

I am trying to add a header to the rich text in a RichTextBox, using VB.NET and Visual Studio 2017. According to the documentation, Richtextbox.rtf should allow me to get or set the rich text including control codes. However, I am unable to set *.rtf to a string containing rich text. I know that the rich text is correct because if I paste it into a *.rtf file, it is displayed correctly.
The test code looks like this:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim hdr As String = "{\header This is a header}"
Dim s As String = RichTextBox1.Rtf
s = s.Insert(s.LastIndexOf("}"c) - 1, hdr)
MsgBox(s)
With RichTextBox1
RichTextBox1.Rtf = s
MsgBox(RichTextBox1.Rtf)
End With
End Sub
The string s is correctly formatted as rich text, but RichTextBox1.Rtf is unchanged after the assignment. What am I missing? If I can't assign RichTextBox1.Rtf this way, is there an alternative?

Thanks again #PerpetualStudent!
The problem appears to be that the RichTextBox1.RTF field does not accept the "{\header This is a header}" control code. That is probably by design because a RichTextBox cannot display a header. I tried putting the control code in a different location in the rich text string, but that didn't work either.
I can edit the rich text in other ways (see below), but I cannot insert the header control code. That's unfortunate because it is part of the rich text standard. Anyhow, now that I know what the problem is, I can come up with a solution. A workaround might be to modify the print and save code of my rich text box print control form to add the header and footer in the print or save actions.
This works:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
With RichTextBox1
Dim s As String = .Rtf
s = s.Replace("Hello", "Good morning")
MsgBox(s)
.Rtf = s
MsgBox(.Rtf)
End With
End Sub

Related

How can I save the content of a rich text box even when the form closes?

This is my first post here, so please don't judge me if I write something wrong ^^
Anyways, I've recently run into an issue with richtextboxes in Visual Basic .NET and WinForms.
Let's say I have a Main form and a Log form. The log form contains a richtextbox which functions as a log. From the main form I'm writing text to the log and I also format the lines, so they have different colors (blue for information, red for error).
Unfortunately, whenever I close and reopen the log form all text that has been written to it is lost.
I've tried saving it to a text file, but that doesn't save the colors of the text.
Is there any way I can save the text and the colors of the lines even when the form closes?
Here's what the excellent suggestion from Shrotter might look like:
Public Class Form1
Private RtfPath As String
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim folder As String = System.IO.Path.GetDirectoryName(Application.ExecutablePath)
RtfPath = System.IO.Path.Combine(folder, "RtbData.rtf")
If System.IO.File.Exists(RtfPath) Then
RichTextBox1.LoadFile(RtfPath)
End If
End Sub
Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
RichTextBox1.SaveFile(RtfPath)
End Sub
End Class
Of course, you should always wrap the loading/saving of the file in a Try/Catch block in case anything goes wrong.

How to fit a long text file field into a listbox?

I'm creating a program that is reading the information for recipes from a text file. I have the text file structured in a way that the list of instructions for each recipe are combined into one field of the text file. However, when I try to display the instructions into a listbox, it displays as one long line, and you can't see the full set of instructions. Is there anyway to manipulate that single field of the text file to continue onto the next line of the listbox when the text fills the space? I've included a picture of my code for displaying other elements of the text file line.
code
Here is what the sample field says in my text file:
In a pan sauté the shallots in olive oil. Add the brussel sprouts. Sauté until vibrant green. Add chopped bacon and balsamic vinegar if desired.
Once again, I just need help on how to get that giant field to fit to my text box. Here is a picture of my form during runtime currently. Thank you!
vb form
You've to control the drawing yourself.
From DrawMode docs, OwnerDrawVariable:
All the elements in the control are drawn manually and can differ in size.
Now, I'm setting the ItemHeight in MeasureItem event, and drawing the text in DrawItem event.
Protected Overrides Sub OnLoad(e As EventArgs)
yourListBox.DrawMode = DrawMode.OwnerDrawVariable
MyBase.OnLoad(e)
End Sub
Private Sub yourListBox_MeasureItem(sender As Object, e As MeasureItemEventArgs) Handles yourListBox.MeasureItem
e.ItemHeight = e.Graphics.MeasureString(yourListBox.Items(e.Index).ToString(), yourListBox.Font, yourListBox.Width).Height + 10
End Sub
Private Sub yourListBox_DrawItem(sender As Object, e As DrawItemEventArgs) Handles yourListBox.DrawItem
If e.Index < 0 Then Return
e.DrawBackground()
e.Graphics.DrawString(yourListBox.Items(e.Index).ToString(), yourListBox.Font, Brushes.Black, e.Bounds)
End Sub

Reading Textbox & 'Grabbing' Line into String Variable vb

Okay, I have a textbox, which contains an IP Address, the texbox is populated by a remote file which IS NOT stored - it's downloaded into memory and then placed in the texbox, so it has no actual file in the systems directories, leaving me unable to use the FileStream method.
So, I want to take the text from textbox1, and look for the word 'IP', once this is found I want it to 'grab' that particular line and place it into another textbox (texbox2). How can I do this?
-Please note, there will only ever be ONE line with the word 'IP' in it, and it will always be the first word on the line.
One way...
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
TextBox2.Text = TextBox1.Lines.Where(Function(x) x.ToUpper.StartsWith("IP")).FirstOrDefault
End Sub
Another way is to use indexof to find where the IP text starts
Dim sresult = TextBox1.Text.IndexOf("IP")
Dim linebreak = TextBox1.Text.IndexOf(vbCrLf, sresult)
TextBox2.Text = TextBox1.Text.Substring(sresult, linebreak - sresult)

Visual Basic Form. How to let users save text file where they want

Private Sub Button7_Click(sender As Object, e As EventArgs) Handles Button7.Click
Dim CurrentDir As String = Environment.CurrentDirectory
Dim OutputFile2 As String = IO.Path.Combine(CurrentDir, "input.txt")
IO.File.WriteAllLines(OutputFile2, Result1.Lines)
End Sub
Right now, I have coding that saves a text file in the current directory. However, I want to have a browse button for users so that they can pick where this text file is saved. How do I proceed this?
I was trying it by my self and I'm having a trouble with using save file dialog. If you can teach me how to use a save file dialog or anyway to write save browse button, I would very appreciate it!
The documentation for the SaveFileDialog object contains an example.
Here is a tutorial on how to implement SaveFileDialog using Toolbox in Visual Studio like you mentioned. The code sample is in C# but it can be easily converted to VB.
Link: www.dotnetperls.com/savefiledialog
Private Sub button1_Click(sender As Object, e As EventArgs)
' When user clicks button, show the dialog.
saveFileDialog1.ShowDialog()
End Sub
Private Sub saveFileDialog1_FileOk(sender As Object, e As CancelEventArgs)
' Get file name.
Dim name As String = saveFileDialog1.FileName
' Write to the file name selected.
' ... You can write the text from a TextBox instead of a string literal.
File.WriteAllText(name, "test")
End Sub

Displaying HTML content inside of a textbox

I'm using the following code, to get my raw HTML string from the URL and display it inside of a (rich) textbox form:
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Me.TransparencyKey = Me.BackColor
Dim client As WebClient = New WebClient()
RichTextBox1.Text = client.DownloadString("http://myurl.com/raw.php")
End Sub
The problem is that, the HTML string isn't converted and I can see the HTML tags inside of a textbox text I mean the Hello <strong>World</strong> isnt converted into the "Hello World".
I know I can use a WebBrowser object, but I would like to set its background color from the white to transparent and that is not allowed as far as I know. Another reason I dont want to use WebBrowser are links, because when the downloaded string has some ... tags, it would be converted but when I would like it to be opened with a default browser, instead of a typical location change in a box.
Is there any solution for this?
A TextBox cannot render HTML. What you need is a modified RichTextBox control that handles HTML. This might help you get started atleast.
Then there's the HtmlTextbox for Windows.Forms control which might suite your needs.