WinForms TextBox that splits at a specified interval

Posted: 05/05/2011

I don’t know that this code is all that useful for anyone, but I thought I’d share it as opposed to just deleting it. It was something I put together in 5 minutes to answer a question on the MSDN forums:

''' <summary>
''' TextBox that will put a carriage return in every set amount of characters (in the WrapAtInterval property)
''' </summary>
''' <remarks>5-5-2011 - blakepell</remarks>
Public Class TextBoxEx
    Inherits TextBox
    Sub New()
    End Sub
    Private Sub TextBoxEx_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles Me.KeyPress
        If Me.Text.Length = 0 Then
            Exit Sub
        End If
        ' The key hasn't been inserted into the text box at this point, so we need to add
        ' a + 1 to it so the length we check is the length that will be in the box.  We need
        ' to get rid of the hidden characters that don't actually show while checking the length.
        Dim buf As String = Me.Text.Replace(vbCrLf, "").Length + 1
        If (Me.Text.Replace(vbCrLf, "").Length + 1) Mod Me.WrapAtInterval = 0 Then
            ' Now, we know we are on a interval of what is set in the property "WrapAtInterval".  So, whenever that interval is
            ' hit, we will execute this code
            ' First, save the position in the text box.
            Dim currentPos As Integer = Me.SelectionStart
            ' Second, add the key and the carriage return.  Then tell the text box that you handled adding it yourself and not
            ' do also add it.
            e.Handled = True
            Me.Text += e.KeyChar & vbCrLf
            ' Third, put the cursor back now that we've updated the text property, we'll add 3 characters to it for the vbCrLf which
            ' is a carriage return AND a line feed (ASCII 13 & 10)
            Me.SelectionStart = currentPos + 3
        End If
    End Sub
    Private _wrapAtInterval As Integer = 5
    Public Property WrapAtInterval() As Integer
            Return _wrapAtInterval
        End Get
        Set(ByVal value As Integer)
            _wrapAtInterval = value
        End Set
    End Property
End Class