RichTextBox and column position

I’ve been prototyping an application for work and had a slight problem. I needed to get the column position of the caret in a RichTextBox. To determine the column position I had to subtract the number of characters in the lines before the caret from the caret character position. The RichTextBox.SelecionStart property gives the caret character position so I’m halfway there. But I couldn’t figure out how to compute the number of characters in the lines before the caret. The RichTextBox methods don’t give that information. So after some investigation I had to go somewhere where I don’t like to go, the Win32 API. So I cracked open Dan Appleman’s Visual Basic Guide to the Win32 API and found out that it’s still relevant in today’s .Net world. I knew that I needed to use the SendMessage function but I didn’t know what message to send. I found the answer on page 1362, EM_LINEINDEX. EM_LINEINDEX “determines the character offset of the first character in the specified line.” In other word exactly what I was looking for. So here’s the final code. I’ve subclassed the RichTextBox into a control that supports the GetCurrentColumn function. I now know the column position in my RichTextBox and everything is roses.

Public Class ColumnTextBox : Inherits RichTextBox

    Private Declare Function SendMessage Lib “user32” _
        Alias “SendMessageA” (ByVal hwnd As IntPtr, ByVal wMsg As Integer, _
        ByVal wParam As Integer, ByVal lParam As Long) As Integer

    Private Const EM_LINEINDEX = &HBB

    Public Function GetCurrentColumn() As Integer

        Dim lineIndex As Integer = SendMessage(Me.Handle, EM_LINEINDEX, -1, 0)
        Return Me.SelectionStart – lineIndex

    End Function

End Class


Now Playing: Stavesacre – At the Moment