如何使用鼠标悬停事件在 RichTextBox 中选择一个单词 [英] How to select a word in a RichTextBox with a mouseover event
问题描述
我在文本框中有一篇长文章.我想复制长篇文章中的一个单词,只需将鼠标移到该单词上并等待 2 秒钟.我不想做任何像突出显示这个词的事情.我可以知道如何让 VB 做到这一点吗?
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 ?
谢谢
推荐答案
我在网上找到了以下代码.(归功于 Siri1008)
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
声明一个公共变量 curWord.
Declare a public variable curWord.
然后,在 RichTextBox 的 MouseMove 事件中,输入curWord = GetWordUnderMouse(Me.RichTextBox1, e.X, e.Y)
Then, in the MouseMove event for the RichTextBox, put curWord = GetWordUnderMouse(Me.RichTextBox1, e.X, e.Y)
在窗体上放置一个计时器并将其间隔设置为 2000.在计时器事件中,放置MsgBox(curWord)Me.Timer1.Enabled = False
Put a Timer on the Form and set it's interval to 2000. In the Timer Event, put MsgBox(curWord) Me.Timer1.Enabled = False
在 RichTextBox MouseHover 事件中,启用计时器.
In the RichTextBox MouseHover event, Enable the Timer.
瞧,这个词被选中了,没有突出显示文本框.当然,如果您只是复制单词,则不需要 msgbox,但您应该可以将其整理出来.
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.
这篇关于如何使用鼠标悬停事件在 RichTextBox 中选择一个单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!