Visual Basic Text API Routines
SendMessage: Determine the Current Line in a Text Box
     
Posted:   Friday July 10, 1998
Updated:   Monday December 26, 2011
     
Applies to:   VB4-32, VB5, VB6, and VB3, VB4-16 with appropriate declarations
Developed with:   VB5, Windows 95
OS restrictions:   None
Author:   VBnet - Randy Birch
     

Related:  

SendMessage: Determine the Number of Lines in a Text Box
SendMessage: Find Text Box Document Size via API
SendMessage: Text Selection Methods via API
SendMessage: Text Range Selection via API
     
 Prerequisites
None.

This method uses SendMessage to retrieve the current line containing the insertion point (the cursor) in a textbox.  A line is defined as a new line after a word-wrap - - it is independent of the number of hard returns in the text.
 BAS Module Code
None.

 Form Code
To the form, add the following code. The demo shows calling the method from the textbox change event:

Option Explicit
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Copyright ©1996-2011 VBnet/Randy Birch, All Rights Reserved.
' Some pages may also contain other copyrights by the author.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Distribution: You can freely use this code in your own
'               applications, but you may not reproduce 
'               or publish this code on any web site,
'               online service, or distribute as source 
'               on any media without express permission.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Private Declare Function SendMessage Lib "user32" _
  Alias "SendMessageA" _
  (ByVal hwnd As Long, _ 
   ByVal wMsg As Long, _ 
   ByVal wParam As Long, _
   lParam As Any) As Long

Private Const EM_LINEFROMCHAR = &HC9


Sub Text1_Change()  

   'get the line the cursor is currently on
    Dim currLine As Long

    On Local Error Resume Next
    currLine = SendMessage(Text1.hwnd, EM_LINEFROMCHAR, -1&, ByVal 0&) + 1
    Label1.Caption = Format$(currLine, "##,###")

End Sub
 Comments
The textbox passed to the SendMessage API must have its multiline property set to true at design time.

The variable passed as wParam specifies the character index of the character contained in the line whose number is to be retrieved <whew!>. If the parameter is -1, either the line number of the current line (the line containing the caret) is retrieved or, if there is a selection, the line number of the line containing the beginning of the selection is retrieved.

The value for lParam must be 0.

 
 

PayPal Link
Make payments with PayPal - it's fast, free and secure!

 
 
 
 

Copyright ©1996-2011 VBnet and Randy Birch. All Rights Reserved.
Terms of Use  |  Your Privacy

 

Hit Counter