In a previous tip, we showed you how to count the lines of text
in a Rich Textbox control. However, if you're going to use this
control to create a text editor, you'll need to know more than
just the number of used lines. For instance, it's often useful
to display the cursor's current position with the control. To do
so, you'll need to call on the SendMessageByNum() API function.
This function uses the following declaration:
Private Declare Function SendMessageByNum Lib "user32" _
Alias "SendMessageA" (ByVal hwnd As Long, ByVal
wMsg As Long, _
ByVal wParam As Long, ByVal lParam As Long) As Long
To obtain the cursor line and index information, you'll pass in
the following to constants, which you also place in the general
declarations section:
Private Const EM_LINEFROMCHAR = &HC9
Private Const EM_LINEINDEX = &HBB
To obtain the appropriate values, you simply pass the applicable
constant into the SendMessageByNum() function, which returns the
position value you've requested. For instance, to obtain the current
line value, you might create a function like so:
Public Function GetCurrentLine(TxtBox As Object) As Long
With TxtBox
GetCurrentLine = SendMessageByNum(.hwnd, EM_LINEFROMCHAR, _
CLng(.SelStart), 0&) + 1
End With
End Function
Of course, with a minor modification, you use the same code to
retrieve the current column, as in:
Public Function GetCurrentColumn(TxtBox As Object) As Long
With TxtBox
GetCurrentColumn = .SelStart - SendMessageByNum(.hwnd, _
EM_LINEINDEX, -1&, 0&) + 1
End With
End Function
The following two Click() events show how you'd use the two procedures,
(assuming you've placed a Rich Textbox control and two Command
buttons on a form):
Private Sub Command1_Click()
MsgBox GetCurrentLine(RichTextBox1)
End Sub
Private Sub Command2_Click()
MsgBox GetCurrentColumn(RichTextBox1)
End Sub