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
 
 
 
 
 
TitleRelate TextBox cursor position to character and line number
KeywordsTextBox, cursor position, character position, line number
CategoriesControls
 
Thanks to Herman Liu.

Use the SendMessage API function to send the messages EM_GETLINECOUNT, EM_LINELENGTH, EM_LINEFROMCHAR, etc.

 
Private Sub command1_Click()
    Dim lineCount As Long
    Dim currLinePos As Long
    Dim overallCursorPos As Long
    Dim chrsBeforeCurrLine As Long
    Dim CurrLineCursorPos As Long
    Dim currLineLen As Long
    
    On Local Error Resume Next
   
     'total number of lines in the text box
    lineCount = SendMessageLong(Text1.hwnd, _
        EM_GETLINECOUNT, 0, 0&)
    Label2.Caption = "No.of lines count (inc blank line if " & _
        "any) = " & CStr(lineCount)
    
     'cursor position in the text box
    overallCursorPos = SendMessageLong(Text1.hwnd, _
        EM_GETSEL, 0, 0&) \ &H10000
    Label3.Caption = "Overall cursor pos (incl CR and LF if " & _
        "any) = " & CStr(overallCursorPos + 1)
   
    'current line pos (Note: zero-based)
    currLinePos = SendMessageLong(Text1.hwnd, _
        EM_LINEFROMCHAR, overallCursorPos, 0&)
    Label4.Caption = "Current line = " & CStr(currLinePos + _
        1)
    
     'number of chrs upto but before start of the current
     ' line
    chrsBeforeCurrLine = SendMessageLong(Text1.hwnd, _
        EM_LINEINDEX, currLinePos, 0&)
    Label5.Caption = "Chars before current line (incl CR " & _
        "and LF if any) = " & CStr(chrsBeforeCurrLine)

     'cursor position in terms of current line only (Note:
     ' zero-based)
    CurrLineCursorPos = overallCursorPos - _
        chrsBeforeCurrLine
    Label6.Caption = "Char pos in current line = " & _
        CStr(CurrLineCursorPos + 1)
    
    'number of characters in current line (Note: with
    ' EM_LINELENGTH, the value of the "wParam"
    'parameter specifies the char index of a char in the
    ' line. If this parameter is -1, the
    'function returns number of unselected characters on
    ' line. "lParam" not used and set to 0).
    currLineLen = SendMessageLong(Text1.hwnd, _
        EM_LINELENGTH, -1, 0&)
    Label7.Caption = "No. of unselected chars in current " & _
        "line = " & CStr(currLineLen)
    
    Text1.SetFocus
End Sub
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated