[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 3109
  • Last Modified:

Replace Text in a string (VB.Net)

I would like to replace text in a string submitted from a RichTextBox.  Ideally i would like to replace the text with an image, for example: if i was to type :) then a smiley image would appear in its place.  the text submitted from the RichTextBox is displayed in another RichTextBox (like a chat program basically)

Language: VB.Net
0
TheMadMonkey
Asked:
TheMadMonkey
  • 12
  • 7
  • 4
  • +2
1 Solution
 
L00MCommented:
...
Dim myStr as String = "Hello :)"

rtb1.Text = ReplaceEmoticons(myStr)
...


Function ReplaceEmoticons(byval str as string) as String
  str = Replace(str, ":)", "<img src='images/smiley.jpg'>")
  str = Replace(str, ":(", "<img src='images/frown.jpg'>")
  '...
  Return str
End Function

Like that?
0
 
L00MCommented:
hmmmm, I think not. You need to convert the emoticon to a picture object instead eh? (I was thinking html....sorry)
0
 
TheMadMonkeyAuthor Commented:
yes each emoticon will be a picture object that needs to be insterted when a user types :) or :P etc (not directly in the box they are typing in, just the output box which is where the chat is displayed)

Thanks
0
Microsoft Certification Exam 74-409

Veeam® is happy to provide the Microsoft community with a study guide prepared by MVP and MCT, Orin Thomas. This guide will take you through each of the exam objectives, helping you to prepare for and pass the examination.

 
malharoneCommented:
i'd recommend storing the text as HTML then RTF .. since HTML is easier to parse/analyze. plus by "linking" images in HTML you'd save space by not embedding them into RTF
0
 
TheMadMonkeyAuthor Commented:
storing the images aren't my concern, its getting them to display in the RichTextBox when a user types :) or :P for example.
0
 
TheMadMonkeyAuthor Commented:
EDIT:  i will not be linking the images from anywhere, the images will be stored as picture objects
0
 
malharoneCommented:
ok...
1) load all the different images in an ImageList -- an array of image or a hashtable
2) set key-preview property to TRUE. and add an event for key-preview. so when you detect user typed the pattern ":)" or ":("  --- in two consecutive evnets, find the appropriate image from the list. Copy it to the clipboard (clipboard.copy) .. and then paste it into the richtextbox (richtbox1.Paste()).


hope this helps
0
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
This is basically what malharone said.

Obviously, the code below could be made far more efficient than what it is but it demonstrates the concept.

I placed three gifs [smiley.gif, wink.gif, sad.gif] in the \bin directory.

Idle_Mind

Public Class Form1
    Inherits System.Windows.Forms.Form

    Private emoticons As New Collection

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim img As Image
        Dim curdir As String = Environment.CurrentDirectory & "\"

        If System.IO.File.Exists(curdir & "smiley.gif") Then
            img = Image.FromFile(curdir & "smiley.gif")
            emoticons.Add(img, "smiley")
        End If
        If System.IO.File.Exists(curdir & "wink.gif") Then
            img = Image.FromFile(curdir & "wink.gif")
            emoticons.Add(img, "wink")
        End If
        If System.IO.File.Exists(curdir & "sad.gif") Then
            img = Image.FromFile(curdir & "sad.gif")
            emoticons.Add(img, "sad")
        End If
    End Sub

    Private Sub RichTextBox1_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles RichTextBox1.TextChanged
        Dim plainText As String
        Dim currentLoc As Integer

        Do
            plainText = RichTextBox1.Text
            currentLoc = InStr(plainText, ":)")
            If currentLoc > 0 Then
                RichTextBox1.SelectionStart = currentLoc - 1
                RichTextBox1.SelectionLength = 2
                Try
                    Clipboard.SetDataObject(emoticons.Item("smiley"))
                    RichTextBox1.Paste()
                Catch ex As Exception
                End Try
            End If
        Loop While currentLoc > 0

        Do
            plainText = RichTextBox1.Text
            currentLoc = InStr(plainText, ";)")
            If currentLoc > 0 Then
                RichTextBox1.SelectionStart = currentLoc - 1
                RichTextBox1.SelectionLength = 2
                Try
                    Clipboard.SetDataObject(emoticons.Item("wink"))
                    RichTextBox1.Paste()
                Catch ex As Exception
                End Try
            End If
        Loop While currentLoc > 0

        Do
            plainText = RichTextBox1.Text
            currentLoc = InStr(plainText, ":(")
            If currentLoc > 0 Then
                RichTextBox1.SelectionStart = currentLoc - 1
                RichTextBox1.SelectionLength = 2
                Try
                    Clipboard.SetDataObject(emoticons.Item("sad"))
                    RichTextBox1.Paste()
                Catch ex As Exception
                End Try
            End If
        Loop While currentLoc > 0
    End Sub
End Class

0
 
TheMadMonkeyAuthor Commented:
well thats SORT of what i want.    all i want is something that will read a string of text and replace words, like "this is cool"   if i want to replace all "is" words that appear in the string to "was", how would i go about doing such a thing?


same concept with inserting the emoticons.   because i want the images to pull from client side, i dont want huge chunks of bytes being transfered from client to server and broadcasted to the other connected clients in the chat and etc.

hope that clears some things up.

Thanks


0
 
_TAD_Commented:


** Not for Points **

Just a quick note: I like the idea.  Personally, I would not put all of the icons/gifs into a directory.  Instead I would create a resx (resource) file that I would read from (and store in an image list, etc, etc).  This will prevent the users from altering your images.  Also, this allows you to have future graphic enhancements with a simple change of a resx file.

Just a thought...
0
 
TheMadMonkeyAuthor Commented:
good idea, TAD, thanks.
0
 
malharoneCommented:
Yes .. _TAD_ is correct. RESX files are the best approach for storing internal resources.
0
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
All true.  My example replaces the text in real time, but you could just as easily send the text across your connection, place it into a richtextbox, and then use code similar to what I posted to replace it after it has been received.

Incidentally, here is how you would replace all occurences of "is" with "was"

    RichTextBox1.Rtf = RichTextBox1.Rtf.Replace("is", "was")

Regards,

Idle_Mind
0
 
TheMadMonkeyAuthor Commented:
Thank You!  that works for replacing text, now all i need is to get it to change :) text to smiley image

0
 
TheMadMonkeyAuthor Commented:
EDIT:  this is a 500 point question.  i'm a newbie to VB.Net so please make the solution as simple as possible for me.  I have not found my solution yet so the question still stands.

Thank You

0
 
malharoneCommented:
ok... how about this .. you can insert ":(", ":)" , ":-", ":|"

you must first make sure you use proper images.

Public Class Form9
    Inherits System.Windows.Forms.Form

#Region " Windows Form Designer generated code "

    Public Sub New()
        MyBase.New()

        'This call is required by the Windows Form Designer.
        InitializeComponent()

        'Add any initialization after the InitializeComponent() call

    End Sub

    'Form overrides dispose to clean up the component list.
    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        If disposing Then
            If Not (components Is Nothing) Then
                components.Dispose()
            End If
        End If
        MyBase.Dispose(disposing)
    End Sub

    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.  
    'Do not modify it using the code editor.
    Friend WithEvents RichTextBox1 As System.Windows.Forms.RichTextBox
    Friend WithEvents TextBox1 As System.Windows.Forms.TextBox
    Friend WithEvents Button1 As System.Windows.Forms.Button
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
        Me.RichTextBox1 = New System.Windows.Forms.RichTextBox
        Me.TextBox1 = New System.Windows.Forms.TextBox
        Me.Button1 = New System.Windows.Forms.Button
        Me.SuspendLayout()
        '
        'RichTextBox1
        '
        Me.RichTextBox1.Location = New System.Drawing.Point(16, 8)
        Me.RichTextBox1.Name = "RichTextBox1"
        Me.RichTextBox1.Size = New System.Drawing.Size(328, 264)
        Me.RichTextBox1.TabIndex = 0
        Me.RichTextBox1.Text = ""
        '
        'TextBox1
        '
        Me.TextBox1.Location = New System.Drawing.Point(16, 280)
        Me.TextBox1.Name = "TextBox1"
        Me.TextBox1.Size = New System.Drawing.Size(280, 20)
        Me.TextBox1.TabIndex = 1
        Me.TextBox1.Text = "TextBox1"
        '
        'Button1
        '
        Me.Button1.Location = New System.Drawing.Point(304, 280)
        Me.Button1.Name = "Button1"
        Me.Button1.Size = New System.Drawing.Size(40, 23)
        Me.Button1.TabIndex = 2
        Me.Button1.Text = "Send"
        '
        'Form9
        '
        Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
        Me.ClientSize = New System.Drawing.Size(536, 405)
        Me.Controls.Add(Me.Button1)
        Me.Controls.Add(Me.TextBox1)
        Me.Controls.Add(Me.RichTextBox1)
        Me.Name = "Form9"
        Me.Text = "Form9"
        Me.ResumeLayout(False)

    End Sub

#End Region

    Private Sub Form9_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        With il.Images
            .Add(New System.Drawing.Bitmap("C:\Program Files\Adobe\Acrobat 6.0\Reader\HowTo\ENU\Images\areatool.gif"))
            .Add(New System.Drawing.Bitmap("C:\Program Files\Adobe\Acrobat 6.0\Reader\HowTo\ENU\Images\attach.gif"))
            .Add(New System.Drawing.Bitmap("C:\Program Files\Adobe\Acrobat 6.0\Reader\HowTo\ENU\Images\perimeter.gif"))
            .Add(New System.Drawing.Bitmap("C:\Program Files\Adobe\Acrobat 6.0\Reader\HowTo\ENU\Images\selecttext.gif"))
            .Add(New System.Drawing.Bitmap("C:\Program Files\Adobe\Acrobat 6.0\Reader\HowTo\ENU\Images\snapshot.gif"))
        End With
    End Sub

    Private Function getImage(ByVal st As String) As Image
        Select Case st
            Case ":)"
                Return il.Images(0)
            Case ":("
                Return il.Images(1)
            Case ":-"
                Return il.Images(2)
            Case Else
                Return il.Images(3)
        End Select
    End Function
    Dim il As New ImageList

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        'Me.RichTextBox1.Text += "aaa"
        Dim txt As String = Me.TextBox1.Text
        Dim ch As Char
        Dim chs() As Char = txt.ToCharArray()
        Dim x As Integer
        For x = 0 To chs.Length - 1
            ch = chs(x)
            If chs(x) = ":" AndAlso (x + 1 < chs.Length) Then
                If (chs(x + 1) = ")" OrElse chs(x + 1) = "(" OrElse chs(x + 1) = "-" OrElse chs(x + 1) = "|") Then
                    Dim i As Image = getImage(ch & chs(x + 1))
                    Clipboard.SetDataObject(i)
                    x += 1
                    Me.RichTextBox1.Paste()
                Else
                    Me.RichTextBox1.AppendText(ch)
                End If
            Else
                Me.RichTextBox1.AppendText(ch)
            End If
        Next
        Me.TextBox1.Text = ""
    End Sub
End Class
0
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
TheMadMonkey,

The code I already posted shows you to change :) to a smiley face.

What part don't you understand?

Idle_Mind
0
 
TheMadMonkeyAuthor Commented:
read my comments and you'll find out
0
 
TheMadMonkeyAuthor Commented:
malharone, your code works great!  only problem is the image backgrounds show up blue and are resizeable in the RTF box :(  any idea's to get images to show properly?  i know, i'm picky, but hey, if you can help me figure this small part out, 500 points are all yours.

Thanks
0
 
TheMadMonkeyAuthor Commented:
EDIT: oh and i noticed the emoticons dont show up when the RichTextBox is set to readonly, which is a problem because i want it to be readonly lol.
0
 
malharoneCommented:
yes .. because paste is "interactive" .. not programmatic.
0
 
malharoneCommented:
well .. this is not foolproof .. but certainly a step forward .. basically i'm setting focus when user tries to do something in RTbox.
i'm also setting readonly off before inserting and on after inserting the icon.
But as you may realize, the "readonly" is buggy. It still lets you resize the image. I'm sure M$'d claim it's a feature -- not a bug.

- malhar


    Private Sub Form9_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        With il.Images
            .Add(New System.Drawing.Bitmap("C:\Program Files\Adobe\Acrobat 6.0\Reader\HowTo\ENU\Images\areatool.gif"))
            .Add(New System.Drawing.Bitmap("C:\Program Files\Adobe\Acrobat 6.0\Reader\HowTo\ENU\Images\attach.gif"))
            .Add(New System.Drawing.Bitmap("C:\Program Files\Adobe\Acrobat 6.0\Reader\HowTo\ENU\Images\perimeter.gif"))
            .Add(New System.Drawing.Bitmap("C:\Program Files\Adobe\Acrobat 6.0\Reader\HowTo\ENU\Images\selecttext.gif"))
            .Add(New System.Drawing.Bitmap("C:\Program Files\Adobe\Acrobat 6.0\Reader\HowTo\ENU\Images\snapshot.gif"))
        End With
    End Sub

    Private Function getImage(ByVal st As String) As Image
        Select Case st
            Case ":)"
                Return il.Images(0)
            Case ":("
                Return il.Images(1)
            Case ":-"
                Return il.Images(2)
            Case Else
                Return il.Images(3)
        End Select
    End Function
    Dim il As New ImageList

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        'Me.RichTextBox1.Text += "aaa"
        Me.RichTextBox1.ReadOnly = False
        Dim txt As String = Me.TextBox1.Text
        Dim ch As Char
        Dim chs() As Char = txt.ToCharArray()
        Dim x As Integer
        For x = 0 To chs.Length - 1
            ch = chs(x)
            If chs(x) = ":" AndAlso (x + 1 < chs.Length) Then
                If (chs(x + 1) = ")" OrElse chs(x + 1) = "(" OrElse chs(x + 1) = "-" OrElse chs(x + 1) = "|") Then
                    Dim i As Image = getImage(ch & chs(x + 1))
                    Clipboard.SetDataObject(i)
                    x += 1
                    Me.RichTextBox1.Paste()
                Else
                    Me.RichTextBox1.AppendText(ch)
                End If
            Else
                Me.RichTextBox1.AppendText(ch)
            End If
        Next
        Me.RichTextBox1.AppendText(vbCrLf)
        Me.TextBox1.Text = ""
        Me.RichTextBox1.ReadOnly = True
    End Sub

    Private Sub RichTextBox1_SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles RichTextBox1.SelectionChanged
        Me.RichTextBox1.Select(Me.RichTextBox1.Text.Length, 0)
    End Sub

    Private Sub RichTextBox1_GotFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles RichTextBox1.GotFocus
        Me.TextBox1.Focus()
    End Sub

    Private Sub RichTextBox1_Enter(ByVal sender As Object, ByVal e As System.EventArgs) Handles RichTextBox1.Enter
        Me.TextBox1.Focus()
    End Sub

    Private Sub RichTextBox1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles RichTextBox1.Click
        Me.TextBox1.Focus()
    End Sub

    Private Sub RichTextBox1_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles RichTextBox1.MouseDown
        Me.TextBox1.Focus()
    End Sub

    Private Sub RichTextBox1_ContentsResized(ByVal sender As Object, ByVal e As System.Windows.Forms.ContentsResizedEventArgs) Handles RichTextBox1.ContentsResized
        Me.TextBox1.Focus()
    End Sub
0
 
TheMadMonkeyAuthor Commented:
Thanks for all of your help!
0
 
malharoneCommented:
glad to help.
i was just searching google and found exactly what you're lookign for..

http://www.codeproject.com/cs/miscctrl/csexrichtextbox.asp

however even this does not solve image resize problem.

- malhar
0
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
No disrespect meant to TheMadMonkey or malharone or anyone else in this thread but did you not look at my code?  It does essentially the same thing.  It places an Image on the clipboard, selects text in a richtextbox and then pastes the image over the selected text.

Anyhoo...

Good Luck to All

Idle_Mind
0
 
TheMadMonkeyAuthor Commented:
your code is nice and all, but it would not compile for me.

sorry :(
0

Featured Post

Vote for the Most Valuable Expert

It’s time to recognize experts that go above and beyond with helpful solutions and engagement on site. Choose from the top experts in the Hall of Fame or on the right rail of your favorite topic page. Look for the blue “Nominate” button on their profile to vote.

  • 12
  • 7
  • 4
  • +2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now