Thursday, September 9, 2010

Selecting word by right clicking richtextbox vb.net

Recently I've searched internet to find a way to select a word in richtextbox by right clicking the word. But ended up with nothing. May be I've not used right key words to search. Anyways here is what i did by referring to the resource. I hope these would be useful to sum1 like me.

Use these line of codes at mouse down event of richtextbox.


Private Sub rtbInput_MouseDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles rtbInput.MouseDown



        ' Getting the word under the mouse clicked loaction
        If e.Button = MouseButtons.Right Then
            Dim CharIndex As Int32
            Dim StartPos As Int32
            Dim EndPos As Int32

            'location of mouse clicked
            CharIndex = rtbInput.GetCharIndexFromPosition(New Point(e.X, e.Y))
            'Locating the end point of the selections
            EndPos = rtbInput.Text.IndexOf(" ", CharIndex)
            'Locating the start point of the selection
            StartPos = rtbInput.Text.LastIndexOf(" ", CharIndex)

            'Checking if the mouse clicked on word 
            If EndPos = -1 Then
                EndPos = 0
            End If
            If StartPos = -1 Then
                StartPos = 0
            End If
            If StartPos > EndPos Then
                Exit Sub
            End If
            'selecting the word under the clicked location
            CharIndex -= StartPos
            rtbInput.Select(StartPos, EndPos - StartPos)
        End If
    End Sub







1 comment:

Wostin said...

It was a good solution for that!

I'll use it, but changing the "indexof" and "lastindexof" to make a search in a string of all chars that don't are words ( i.e. ".,;:!@$% etcetera)

Thanks Ali! ;)