Library code snippets

Add tab spaces in the RichTextBox

When you use the Rich Textbox control on a form, you'll often want to
let users add tabs to their input. If the Rich Textbox is the only
control on the form, then pressing the [Tab] key inserts the requested
tab space into the text. Most likely, however, you'll have more than one
control on the form, in which case pressing the [Tab] key moves the
focus from the Rich Textbox to another control.

To prevent this behavior, you could simply set each control's TabStop
property to False. This prevents users from tabbing between ANY
controls--but does let them enter tabs into the Rich Textbox.

Chances are, though, you want to give users the ability to tab between
controls AND enter tabs in the Rich Textbox. Fortunately, VB provides
the tools for you to do so in the Rich Textbox control's KeyDown()
event.

As you probably know, the Rich Textbox fires this event when a user
presses a key while the control has the focus. Like all KeyDown()
events, you can use code to determine which key the user pressed and
react accordingly. To capture the Tab key and insert a tab space into
the Rich Textbox control's edit area, we could use the following:

Private Sub RichTextBox1_KeyDown(KeyCode _
     As Integer, Shift As Integer)
Dim mblnTabPressed As Boolean

mblnTabPressed = (KeyCode = vbKeyTab)
If mblnTabPressed Then
    RichTextBox1.SelText = vbTab
    KeyCode = 0
End If
End Sub

Comments

  1. 11 Feb 2005 at 14:33

    I have inserted the suggested code, and it works, but only when the textbox is not empty.


    For instance, I can enter a text, e.g. "Iwantatab". Then, I can place my cursor between the "I" and "w" and press <TAB>. This works.


    However, I want to be able to enter "I<TAB>want<TAB>a<TAB>tab". When I insert the first <TAB>, nothing happens (the cursor jumps to back to the first position).


    How can I fix this?


  2. 26 Jul 2004 at 10:51

    You also could simply tell the richtextbox to accept tabs


    Code:
    Me.RichTextBox1.AcceptsTab = True

  3. 01 Jan 1999 at 00:00

    This thread is for discussions of Add tab spaces in the RichTextBox.

Leave a comment

Sign in or Join us (it's free).