How to select a word in a RichTextBox with a mouseover event

☆樱花仙子☆ 提交于 2019-12-13 01:49:42

问题


I have a long essay in a textbox. I want to copy a word in the long essay by simply move my mouse to that word and wait for 2 seconds. I do NOT want to do anything like highlight the word. May I know how to make VB do that ?

Thanks


回答1:


I found the following code online. (Credit goes to Siri1008)

Public Function GetWordUnderMouse(ByRef Rtf As System.Windows.Forms.RichTextBox, ByVal X As Integer, ByVal Y As Integer) As String
    On Error Resume Next
    Dim POINT As System.Drawing.Point = New System.Drawing.Point()
    Dim Pos As Integer, i As Integer, lStart As Integer, lEnd As Integer
    Dim lLen As Integer, sTxt As String, sChr As String
    '
    POINT.X = X
    POINT.Y = Y
    GetWordUnderMouse = vbNullString
    '
    With Rtf
        lLen = Len(.Text)
        sTxt = .Text
        Pos = Rtf.GetCharIndexFromPosition(POINT)
        If Pos > 0 Then
            For i = Pos To 1 Step -1
                sChr = Mid(sTxt, i, 1)
                If sChr = " " Or sChr = Chr(13) Or i = 1 Then
                    'if the starting character is vbcrlf then
                    'we want to chop that off
                    If sChr = Chr(13) Then
                        lStart = (i + 2)
                    Else
                        lStart = i
                    End If
                    Exit For
                End If
            Next i
            For i = Pos To lLen
                If Mid(sTxt, i, 1) = " " Or Mid(sTxt, i, 1) = Chr(13) Or i = lLen Then
                    lEnd = i + 1
                    Exit For
                End If
            Next i
            If lEnd >= lStart Then
                GetWordUnderMouse = Trim(Mid(sTxt, lStart, lEnd - lStart))
            End If
        End If
    End With
End Function

Declare a public variable curWord.

Then, in the MouseMove event for the RichTextBox, put curWord = GetWordUnderMouse(Me.RichTextBox1, e.X, e.Y)

Put a Timer on the Form and set it's interval to 2000. In the Timer Event, put MsgBox(curWord) Me.Timer1.Enabled = False

In the RichTextBox MouseHover event, Enable the Timer.

Voila, the word is chosen, without highlighting the textbox. Of course, you do not need the msgbox if you are just copying the word, but you should be able to sort that out.



来源:https://stackoverflow.com/questions/11389601/how-to-select-a-word-in-a-richtextbox-with-a-mouseover-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!