Wednesday, January 17, 2007

How to find out the number of lines taken up in a TextBox control?

Question
How do I find out the number of lines taken up in a TextBox control?

Answer
Before we discuss the solution, let's recap that the TextBox control supports multiline using the Multiline property. If you set it to True, then you can span your text input over multiple lines. It also exposes the Lines property (supported only on .NET framework but not .NET CF), where you can check how many lines are stored in the TextBox control. However, the Lines property only reports the number of lines separated by a carriage return character. Hence, if you have a single long line that spans more than the width of the TextBox control, it would still report that you have a single line in it.

To really count the number of lines in it, you have to use P/Invoke.

.NET CF Solution
Declare the functions as follows:

Public Class Form1
<Runtime.InteropServices.DllImport("coredll.dll")> _
Shared Function SendMessage( _

ByVal hwnd As IntPtr, ByVal msg As Integer, _
ByVal wParam As Integer, ByVal lParam As Integer) As Integer
End Function

<Runtime.InteropServices.DllImport("coredll.dll")> _
Shared Function GetCapture() As IntPtr
End Function


Then, declare the constant and variable:

Private Const EM_GETLINECOUNT = &HBA
Dim hnd As IntPtr

Finally, do this in your code:

TextBox1.Capture = True
hnd = GetCapture()
TextBox1.Capture = False
Dim linecount as Integer = SendMessage(hnd, EM_GETLINECOUNT, 0, 0)


.NET Solution
Declare the following function:

Public Class Form1
Private Declare Function SendMessageAsLong Lib "user32" _
Alias "SendMessageA" ( _
ByVal hWnd As Integer, ByVal wMsg As Integer, _
ByVal wParam As Integer, ByVal lParam As Integer) As Integer


Define the following constant:

Private Const EM_GETLINECOUNT = &HBA


Finally, do this in your code:

Dim linecount As Long = SendMessageAsLong(TextBox1.Handle, EM_GETLINECOUNT, 0, 0)






Do you want more information about a prospective babysitter? Searching for an old relative? A people finder website can often help in many ways.

No comments: