How to Determine the Number of Lines in a Textbox

This method is straightforward: it uses SendMessage to retrieve the number of lines in a textbox.  A line to this method is defined as a new line after a word-wrap; it is independent of the number of hard returns in the text.

Declarations

Place the following API declare code into the general declarations area of a bas module.   If using VB4-32 or VB5, and this is a one-form project, the declares below could be placed into the general declaration section of the form instead, with all Public references changed to Private.

Option Explicit

Public Declare Function SendMessageLong Lib _
    "user32" Alias "SendMessageA" _
    (ByVal hwnd As Long, _ 
     ByVal wMsg As Long, _ 
     ByVal wParam As Long, _
     ByVal lParam As Long) As Long

Public Const EM_GETLINECOUNT = &HBA

Form Code

Sub Text1_Change()
    Dim lineCount as Long
    On Local Error Resume Next
  
   'get/show the number of lines in the edit control
    lineCount = SendMessageLong(Text1.hwnd, EM_GETLINECOUNT, 0&, 0&)
    Label1 = Format$(lineCount, "##,###")
End Sub

Comments

The textbox passed to the SendMessage API must have its multiline property set to true at design time. The EM_GETLINECOUNT message does not pass additional parameters to the API in the wParam or lParam variables. These must be 0.


Flash Poker | Pro-Built Construction | Free Poker Games | Testamentalb | Shades