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

You might also like...

Comments

ElementK Journals

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“We better hurry up and start coding, there are going to be a lot of bugs to fix.”