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
 
 
 
 
 
 
TitleTrack the text insertion position as the user types
KeywordsTextBox, cursor position, character position, line number
CategoriesControls
 
Thanks to Herman Liu.

Subroutine DispCaretPos uses the SendMessage API function to send the messages EM_LINEFROMCHAR, EM_LINEINDEX, etc. to get the cursor's position.

 
Private Sub DispCaretPos()
    On Local Error Resume Next
    'cursor position in the text box (incl CR & LF if any)
    '(Note zero-based)
    overallCursorPos = SendMessageLong(text1.hwnd, _
        EM_GETSEL, 0, 0&) \ &H10000
    'current line pos (Note: zero-based)
    currLinePos = SendMessageLong(text1.hwnd, _
        EM_LINEFROMCHAR, overallCursorPos, 0&)
    'number of chrs upto but before start of the current
    ' line
    ' (incl CR & LF f any)
    chrsBeforeCurrLine = SendMessageLong(text1.hwnd, _
        EM_LINEINDEX, currLinePos, 0&)
    'cursor position in terms of current line only (Note:
    ' zero-based)
    '
    CurrLineCursorPos = overallCursorPos - _
        chrsBeforeCurrLine
    text1.SetFocus
    ' Note, for example, if you only have 2 sections of the
    ' status
    ' bar, then change 3 to 2 below.
    StatusBarMsg "Pos: " & CStr(currLinePos + 1) & ":" & _
    CStr(CurrLineCursorPos + 1) & Space(1), 1
End Sub
 
When the text changes, keys are pressed, the mouse is clicked, etc., the program calls DispCaretPos to update the cursor's position.
 
Private Sub Text1_Change()
    DispCaretPos
End Sub

Private Sub Text1_Click()
    DispCaretPos
End Sub

Private Sub Text1_KeyUp(KeyCode As Integer, Shift As _
    Integer)
    DispCaretPos
End Sub
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated