What's New
Q & A
Tip Jar
C# Helper...
Follow VBHelper on Twitter
MSDN Visual Basic Community
TitleTrack the cursor position in a RichTextBox
KeywordsRichTextBox, cursor position, character position, line number
In the KeyDown, KeyUp, MouseDown, and Mouseup event handlers, call routine CheckPosition. This routine uses SendMessage to send the TextBox the EM_GETSEL message to get the caret's position. Normally SendMessage returns the selection's start and end positions as the high and low parts of its return value. If the positions are too big, however, they won't both fit. The program uses a different call to SendMessage that passes a reference to Long integers as parameters to SendMessage and the API call saves the positions in those parameters. Notice how the code uses a specially declared version of SendMessage that takes those parameters ByRef.

The code then sends the message EM_LINEFROMCHAR to get the caret's line number and EM_LINEINDEX to get the number of characters before the caret's line. It uses these values to calculate the row and column.

Private Declare Function SendMessage Lib "user32" Alias _
     "SendMessageA" (ByVal hwnd As Long, ByVal wMsg As

Private Declare Function SendMessageReferenceParams Lib _
    "user32" Alias "SendMessageA" (ByVal hwnd As Long, _
    ByVal wMsg As Long, ByRef wParam As Long, ByRef lParam _
    As Long) As Long

Private Sub CheckPosition()
Dim start_pos As Long
Dim end_pos As Long
Dim row As Long
Dim col As Long

    SendMessageReferenceParams _
        Text1.hwnd, EM_GETSEL, start_pos, end_pos

    row = SendMessage(Text1.hwnd, EM_LINEFROMCHAR, _
        start_pos, 0) + 1
    col = start_pos - SendMessage(Text1.hwnd, EM_LINEINDEX, _
        -1, 0) + 1

    lblPosition.Caption = "(" & Format$(row) & ", " & _
        Format$(col) & ")"
End Sub
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.