vb.net 2010 append text always at top of a richtextbox - vb.net

I have create a simple function to append text to a Richtextbox. I want that this text is append always on top scrolling the old text to the bottom.
Private Sub BoxMessaggio(ByVal testo As String, ByVal errore As Integer)
Me.ActiveControl = RichTextBox1
RichTextBox1.Focus()
If errore Then
RichTextBox1.SelectionColor = Color.Red
Else
RichTextBox1.SelectionColor = Color.Black
End If
RichTextBox1.AppendText(testo + vbNewLine)
RichTextBox1.SelectionStart = RichTextBox1.Text.Length
'RichTextBox1.Select(RichTextBox1.TextLength, 0)
RichTextBox1.ScrollToCaret()
End Sub
I call the function in this way:
BoxMessaggio(Now + ": " + ex.Message, 1)
I tried a lot of different solutions found here on StackOverflow or in some forums but no one works for me, text is always add at the bottom....

Treat the RichTextBox1.Text as a String (because it is), call Insert, and place the new text at the front of the strong.
RichTextBox1.Text = RichTextBox1.Text.Insert(0, testo + vbNewLine)
As for the scrolling. Don't call Focus or ScrollToCaret and it will stay at the top viewing the most recently added text.

Related

How do I add a new line without deleting text in a RichTextBox and change it's colour in VB.Net?

I can't seem to find the answer anyway. But my Question is;
In visual basic I want to make something called a problem panel and to test it I am making a debug. It uses a progress bar and timer. Here is some of the code so far.
ProgressBar1.Increment(1)
If ProgressBar1.Value = 1 Then
RichTextBox1.Text = "A developer debug has been executed, please wait"
End If
If ProgressBar1.Value = 3 Then
RichTextBox1.SelectionStart = RichTextBox1.Text.Length + 1
RichTextBox1.Text &= "."
End If
If ProgressBar1.Value = 5 Then
RichTextBox1.SelectionStart = RichTextBox1.Text.Length + 1
RichTextBox1.Text &= "."
End If
If ProgressBar1.Value = 7 Then
RichTextBox1.SelectionStart = RichTextBox1.Text.Length + 1
RichTextBox1.Text &= "."
End If
If ProgressBar1.Value = 10 Then
RichTextBox1.Text &= Environment.NewLine & "Testing Warnings"
RichTextBox1.SelectionColor = Color.Yellow
End If
If ProgressBar1.Value = 15 Then
RichTextBox1.SelectionColor = Color.Yellow
RichTextBox1.Text += Environment.NewLine + "Warning"
End If
Basically all it does is create a line, adds a new one and continues typing text. But I can't get it to add a new line. Print 'Warnings' and change that text to Yellow. But using all the code on the internet it stays white?
If anyone can help, it would be much appreciated.
If it's not clear let me summarize:
*Print's text and keeps everything white.
*Prints a new line with everything staying in the RichTextBox.
*The Text will say, Critical, Warning, Information, etc.
*And It needs to change the colour of the text but not change all of the other printed text colour.
Thanks in advance
Here is a subroutine that will help you:
Private Sub AppendTextWithColor(rich_text_box As RichTextBox, color As Color, text As String)
Dim length_before = rich_text_box.TextLength
rich_text_box.AppendText(text)
Dim length_after = rich_text_box.TextLength
rich_text_box.SelectionStart = length_before
rich_text_box.SelectionLength = length_after - length_before
rich_text_box.SelectionColor = color
End Sub
It allows you to append some text to the RichTextBox with a specific color.
You can use it like this:
AppendTextWithColor(RichTextBox1, Color.Yellow, Environment.NewLine + "Warning")
It works by recording the length of the RichTextBox's text before and after appending the new text. It then sets the SelectionStart and SelectionLength based on the recorded lengths to select the appended text. It then changes the color of the selected text using the SelectionColor property.

Highlight all lines that contain "admin" in a richtextbox

I am Making a chat for my Game launcher, when you launch it up theres a button that Opens a Chat Forum with a richtextbox on it that it refreshes/timer checks when the text has changed in the txt file on the server has changed from textbox1 then it will reprint the text but thats not the problem, i have an admin panel for it, but i want to highlight lines where there is "!ADMINISTRATOR!" in it so it shows the user is an admin and it highlighted to show what he is saying. i've tried this
Dim index As Integer = Me.RichTextBox1.Find("!ADMINISTRATOR!")
If index <> -1 Then
Dim lineindex As Integer = Me.RichTextBox1.GetLineFromCharIndex(index)
Dim first As Integer = Me.RichTextBox1.GetFirstCharIndexFromLine(lineindex)
Dim last As Integer = Me.RichTextBox1.GetFirstCharIndexFromLine(lineindex + 1)
If last = -1 Then last = Me.RichTextBox1.TextLength
Me.RichTextBox1.Select(first, last - first)
Me.RichTextBox1.SelectionBackColor = Color.Yellow
End If
But that works, in a way, it does not always highlight it, while it will highlight sometimes, it also may highlight the text a just just put, but that i don't mind, the main problem is that it only highlights the First line with the text in it, so if the admin posts a message on it it will highlight <3 but then a user will chat and then admin posts another message, it only highlights the first line that contains that text. if you need any more info oh and for testing purposes im using a local file on my pc, ive tested the ftp it works, but just to save time im using a txt file this is the code i use for the timer
Private Sub Timer1_Tick(sender As System.Object, e As System.EventArgs) Handles Timer1.Tick
If (System.IO.File.ReadAllText(Get_Directory_Current() & "\FilesDB\Chat\Chat.txt") = RichTextBox1.Text) Then
Else
Try
RichTextBox1.Text = System.IO.File.ReadAllText(Get_Directory_Current() & "\FilesDB\Chat\Chat.txt")
RichTextBox1.SelectionStart = RichTextBox1.Text.Length
RichTextBox1.ScrollToCaret()
ColorChat() ' this is the color chat that kinda dont work
Catch ex As Exception
End Try
End If
End Sub
if you can help thanks :) but for now i'm just trying new things. i guess it would kinda work a bit like syntax highlighting if you make it highlight a line instead of word.
Oh and if you wanted to know this is how i add the text to the chat / formatting
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
RichTextBox1.AppendText("<[" & Get_Time() & " " & strDate & "] " & "!ADMINISTRATOR!" & " | " & Environment.UserName & "> " & TextBox3.Text & vbNewLine)
End Sub
Use String.Replace() to inject the Rtf formatting where your target string appears.
Dim stringToFind = "!ADMINISTRATOR!"
Dim txt = Me.RichTextBox1.Text
Dim sb = New System.Text.StringBuilder()
sb.Append("{\rtf1\ansi\deff0 {\colortbl;\red0\green0\blue0;\red255\green0\blue0;}")
sb.Append(txt.Replace(stringToFind, String.Format("\cf2{0}\cf1", stringToFind)))
sb.Append("}")
Me.RichTextBox1.Rtf = sb.ToString()

autoscroll to bottom of multiline textbox being updated by backgroundworker

I have a background worker control that is set to perform a task, and update a multiline text box on my main UI using a delegate procedure. this is all working perfectly, however once the updating scrolls off the bottom of the text box, the scroll bars appear, but the continuous refreshing causes the text box to stay locked at the top. Ideally, I would like the text box to auto-scroll itself to the bottom to show the latest entry in real-time. What would be the best way to implement this?
I have tried using the scrolltocaret() method, with and without a SelectionStart = txtlog.Text.Length command preceding it. perhaps I'm putting it in the wrong place?
some code samples below:
Delegate code:
Delegate Sub updateresults_delegate(ByVal textbox As TextBox, ByVal text As String)
Private Sub updatelog_threadsafe(ByVal textbox As TextBox, ByVal text As String)
If textbox.InvokeRequired Then
Dim mydelegate As New updateresults_delegate(AddressOf updatelog_threadsafe)
Me.Invoke(mydelegate, New Object() {textbox, text})
'Me.txtlog.SelectionStart = txtlog.Text.Length
'Me.txtlog.ScrollToCaret()
Else
textbox.Text = text
End If
End Sub
main backgroundworker activity:
For i As Integer = val1 To val2
'generate an IP address from split host parts and current value of i
host = s1(0) & "." & s1(1) & "." & s1(2) & "." & i
Try 'attempt to ping the IP
Dim reply As PingReply = pingsender.Send(host, timeoutval, buffer, options)
If reply.Status = IPStatus.Success Then
name = System.Net.Dns.GetHostEntry(host)'get DNS entry
resulttext += String.Format("{1} - {2}: reply: Bytes={3} time{4} TTL={5}{0}", vbCrLf, name.HostName, reply.Address.ToString, reply.Buffer.Length, getms(reply.RoundtripTime), reply.Options.Ttl) 'print out success text
Else
resulttext += String.Format(" {1}: Ping failed. {2}{0}", vbCrLf, host, reply.Status.ToString) 'print out fail text
End If
updatelog_threadsafe(txtlog, resulttext) 'send text to textbox
System.Threading.Thread.Sleep(1000)
Catch ex As Exception
End Try
Next
I guess my main question is: I'm pretty certain that the textbox.scrolltocaret() is the correct method to use for what I want, but where is the best place for me to put it? I've tried it in the delegate, the main backgroundworker, as well as before & after the runworkerasync() method. none of these worked, and now I'm stumped!
Try it this way:
'textbox.Text = text
textbox.AppendText(text)
The code you commented out wasn't running on the GUI thread, and as M Granja pointed out, AppendText will automatically scroll to the appended text in the box, so no need to call ScrollToCaret.
xxx.SetFocus ' xxx = the name of the textbox
SendKeys "^{END}" ' pop to last line

ASCII Conversion Tool Help VB.NET

I'm trying to make something along the lines of the Branah Unicode Converter to decode lines like this for instance: [99,97,108,108,32,99]. http://www.branah.com/unicode-converter. I found this. I'm guessing the form has a textbox and 2 buttons. One is using Asc to get the textbox's ASCII code and the other using Chr to convert the ASCII code in the textbox into a character.
So, last time I posted this, it got closed because it wasn't "a real question". Let me be blunt. I haven NO idea how to get this working. Labeling of things is very confusing. What do I declare Text1, Text2, Text3 and Label 6 as because it's giving me the error that they're not declared? I'm also getting an error that TextBox1 cannot be converted to an integer from this line: Text2 = Text2 + Chr(TextBox1). How do I fix that? Am I not importing something that I should be?
Private Sub EncodeButton_Click()
'Code the character
TextBox1 = Asc(Text1)
'clears text box
Text1 = ""
' adds the coded character to the textbox (Textbox1)
LABEL6 = LABEL6 + "," + TextBox1
' set focus to textbox
Text1.SetFocus
'decodes the coded character
Text2 = Text2 + Chr(TextBox1)
End Sub
Private Sub DecodeButton_Click()
'this part decodes the coded number
TextBox1 = Text3
Text3 = ""
LABEL6 = LABEL6 + "," + TextBox1
Text2 = Text2 + Chr(TextBox1)
Text3.SetFocus
End Sub
Here's how to make this code work in VB.NET:
Create a new Windows Forms project.
In the project there is a form, open it and create the following items:
Three TextBoxes, named Text1, Text2, Text3
Two Buttons, named EncodeButton and DecodeButton
A Label named Label6
Right click the form in solution explorer and select "View Code".
Paste the following code into the code window:
Public Class Form1
Private Sub EncodeButton_Click(sender As System.Object, e As System.EventArgs) Handles EncodeButton.Click
Dim sTextBox1 As String
sTextBox1 = Asc(Text1.Text)
Text1.Text = ""
Label6.Text = Label6.Text & "," & sTextBox1
Text1.Focus()
Text2.Text = Text2.Text + Chr(sTextBox1)
End Sub
Private Sub DecodeButton_Click(sender As System.Object, e As System.EventArgs) Handles DecodeButton.Click
Dim sTextBox1 As Integer
sTextBox1 = Val(Text3.Text)
Text3.Text = ""
Label6.Text = Label6.Text & "," & sTextBox1
Text2.Text = Text2.Text & Chr(sTextBox1)
Text3.Focus()
End Sub
End Class
Run the project.
Type a single letter into Text1 and click EncodeButton
Type a number into Text3 (try one of the numbers that appeared in Label6 first) and click DecodeButton
This should accomplish everything the sample you pasted was designed to accomplish. If you have difficulty with any of these steps, I suggest looking up a good Windows Forms tutorial online.
Part of your problem is probably that you need to understand that controls like TextBoxes have properties and methods.
So, to GET the value from a TextBox called Text1 and SET it to a TextBox called TextBox1 you'd do this:
TextBox1.Text = Asc(Text1.Text)
If you type in the name of a control and hit the fullstop (".") character afterwards, the intellisense will give you a very helpful list of propertyies and methods you can use.
If you've copied this code from somewhere else, you may also need to create a Form, and drag/drop some TextBox controls onto it and give then names to match your code.

Is there a difference between MsgBox and MessageBox.Show?

Is there a difference between the following two?
msgbox()
messagebox.show()
Some tutorials use msgbox(), and some use the other, messagebox.show()---I see that both can have an editable style, but I was wondering: Why are there two?
Is it to accommodate older programmers (who have learnt on an older version of Visual Basic)?
So in that case, which one should I use in Visual Basic 2010 (Visual Studio 2010)?
MsgBox() is the same as Messagebox.Show().
It exists for VB6 programmers who are used to it.
There are no rules on which one to use, but since MsgBox simply ends up delegating to MessageBox, I personally would go directly with MessageBox.
Here is the source code for Msgbox. As you can see it doesn't do anything particularly interesting before calling MessageBox.Show.
<MethodImpl(MethodImplOptions.NoInlining), HostProtection(SecurityAction.LinkDemand, Resources:=HostProtectionResource.UI)> _
Public Shared Function MsgBox(ByVal Prompt As Object, ByVal Optional Buttons As MsgBoxStyle = 0, ByVal Optional Title As Object = new Object()) As MsgBoxResult
Dim owner As IWin32Window = Nothing
Dim text As String = Nothing
Dim titleFromAssembly As String
Dim vBHost As IVbHost = HostServices.VBHost
If (Not vBHost Is Nothing) Then
owner = vBHost.GetParentWindow
End If
If ((((Buttons And 15) > MsgBoxStyle.RetryCancel) OrElse ((Buttons And 240) > MsgBoxStyle.Information)) OrElse ((Buttons And &HF00) > MsgBoxStyle.DefaultButton3)) Then
Buttons = MsgBoxStyle.OkOnly
End If
Try
If (Not Prompt Is Nothing) Then
[text] = CStr(Conversions.ChangeType(Prompt, GetType(String)))
End If
Catch exception As StackOverflowException
Throw exception
Catch exception2 As OutOfMemoryException
Throw exception2
Catch exception3 As ThreadAbortException
Throw exception3
Catch exception9 As Exception
Throw New ArgumentException(Utils.GetResourceString("Argument_InvalidValueType2", New String() { "Prompt", "String" }))
End Try
Try
If (Title Is Nothing) Then
If (vBHost Is Nothing) Then
titleFromAssembly = Interaction.GetTitleFromAssembly(Assembly.GetCallingAssembly)
Else
titleFromAssembly = vBHost.GetWindowTitle
End If
Else
titleFromAssembly = Conversions.ToString(Title)
End If
Catch exception4 As StackOverflowException
Throw exception4
Catch exception5 As OutOfMemoryException
Throw exception5
Catch exception6 As ThreadAbortException
Throw exception6
Catch exception13 As Exception
Throw New ArgumentException(Utils.GetResourceString("Argument_InvalidValueType2", New String() { "Title", "String" }))
End Try
Return DirectCast(MessageBox.Show(owner, [text], titleFromAssembly, (DirectCast(Buttons, MessageBoxButtons) And DirectCast(15, MessageBoxButtons)), (DirectCast(Buttons, MessageBoxIcon) And DirectCast(240, MessageBoxIcon)), (DirectCast(Buttons, MessageBoxDefaultButton) And DirectCast(&HF00, MessageBoxDefaultButton)), (DirectCast(Buttons, MessageBoxOptions) And DirectCast(-4096, MessageBoxOptions))), MsgBoxResult)
End Function
There is a difference when you are attempting to mix icons with different buttons. MsgBox has predefined styles (there may be a way to create new styles).
For example:
MsgBox("Do you wish to save changes?", MsgBoxStyle.YesNoCancel, "Save Changes")
^ This will display a box with Yes, No and Cancel buttons without an icon.
MsgBox("Do you wish to save changes?", MsgBoxStyle.Question, "Save Changes")
^ This will display a box with a Question mark icon but with ONLY an OK button.
MessageBox.Show("Do you wish to save changes?", "Save Changes", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question)
^ This will display a box with Yes, No and Cancel buttons AND a Question mark icon.
As you can see, using MessageBox.Show enables you to have any buttons you want with any icon.
But the really nice thing about MsgBox is that it can be SystemModal e.g. If MsgBox("There is a new Quick Message!" & Environment.NewLine & "Do you want to read it now?", MsgBoxStyle.Information + MsgBoxStyle.YesNo + MsgBoxStyle.SystemModal, "Quick Message") = MsgBoxResult.Yes Then...
I couldn't find a simple way of making If MessageBox.Show(... to be SystemModal.
My messages now get full prominence on screen. Yippee.
According to this site and the answers so far to my own question (see remark), as well my inability to display a specific help file using the msgbox function, I'd have to say use messagebox rather than msgbox if you want to show help. The msgbox function displays a help button, but apparently there is no way to put a helpfile in it! I'm showing the code I played around with below, and there is also a good code sample on the first link.
Imports Microsoft.visualbasic 'have to have this namespace to use msgbox
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim Helpfilepath As String = "C:\Windows\Help\mui\0409\aclui.chm"
Dim msgresult As Byte
'BTW, Must use 0 for BLANK PARAMETER. Using messageboxoptions.defaultdesktoponly errors out with help btn.
msgresult = MessageBox.Show("Text", "Messagebox", 0, _
0, 0, 0, Helpfilepath)
'displays help button, but how do you display the help file?
msgresult = MsgBox("Text", MsgBoxStyle.MsgBoxHelp, "msgbox")
'BTW, must use dialogresult rather than messageboxresult with windows forms
If msgresult = DialogResult.Yes Then
'etc
End If
End Sub
End Class
The message box created using MsgBox() has a title of the form which created it, whereas the message box window created by MessageBox.Show() does not have any title.