Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleDisplay the word under the mouse in a RichTextBox inside a Tooltip
DescriptionThis example shows how to display the word under the mouse in a RichTextBox inside a Tooltip in Visual Basic 6. It sends the RichTextBox the EM_CHARFROMPOS message to get the character under the mouse's position. It then figures out which word contains the character and displays it in a Tooltip.
KeywordsRichTextBox, TextBox, word, mouse, cursor
CategoriesControls, Tips and Tricks, API
 
Thanks to Gamal.

Subroutine RichWordOver sends the RichTextBox the EM_CHARFROMPOS message to get the character under the mouse's position. It then figures out which word contains the character.

 
' Return the word the mouse is over.
Public Function RichWordOver(rch As RichTextBox, X As _
    Single, Y As Single) As String
Dim pt As POINTAPI
Dim pos As Integer
Dim start_pos As Integer
Dim end_pos As Integer
Dim ch As String
Dim txt As String
Dim txtlen As Integer

    ' Convert the position to pixels.
    pt.X = X \ Screen.TwipsPerPixelX
    pt.Y = Y \ Screen.TwipsPerPixelY

    ' Get the character number
    pos = SendMessage(rch.hWnd, EM_CHARFROMPOS, 0&, pt)
    If pos <= 0 Then Exit Function

    ' Find the start of the word.
    txt = rch.Text
    For start_pos = pos To 1 Step -1
        ch = Mid$(rch.Text, start_pos, 1)
        ' Allow digits, letters, and underscores.
        If Not ( _
            (ch >= "0" And ch <= "9") Or _
            (ch >= "a" And ch <= "z") Or _
            (ch >= "A" And ch <= "Z") Or _
            ch = "_" _
        ) Then Exit For
    Next start_pos
    start_pos = start_pos + 1

    ' Find the end of the word.
    txtlen = Len(txt)
    For end_pos = pos To txtlen
        ch = Mid$(txt, end_pos, 1)
        ' Allow digits, letters, and underscores.
        If Not ( _
            (ch >= "0" And ch <= "9") Or _
            (ch >= "a" And ch <= "z") Or _
            (ch >= "A" And ch <= "Z") Or _
            ch = "_" _
        ) Then Exit For
    Next end_pos
    end_pos = end_pos - 1

    If start_pos <= end_pos Then _
        RichWordOver = Mid$(txt, start_pos, end_pos - _
            start_pos + 1)
End Function
 
When the user moves the mouse over the RichTextBox, its MouseMove event handler calls RichWordOver and saves the result in the control's ToolTipText property.
 
Private Sub rchMainText_MouseMove(Button As Integer, Shift _
    As Integer, X As Single, Y As Single)
Dim txt As String

    txt = RichWordOver(rchMainText, X, Y)
    If rchMainText.ToolTipText <> txt Then _
        rchMainText.ToolTipText = txt
End Sub
 
You could modify this example to look for key phrases and display corresponding detail text or definitions instead of the words themselves.
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated