Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleLet the user reposition tabs in a RichTextBox
KeywordsRichTextBox, rich text, rtf, tab, drag, reposition
CategoriesControls
 
Place a set of label controls over the RichTextBox to mark the tabs. In the labels' MouseDown event handler, start dragging. In the MouseMove event handler, move the label to its new position. In the MouseUp event handler, call subroutine SetTabs to set the tabs.
 
' Start dragging the tab marker.
Private Sub lblTab_MouseDown(Index As Integer, Button As _
    Integer, Shift As Integer, X As Single, Y As Single)
    m_DraggingMarker = Index
    m_StartX = X
End Sub

' Continue dragging the tab marker.
Private Sub lblTab_MouseMove(Index As Integer, Button As _
    Integer, Shift As Integer, X As Single, Y As Single)
    ' Do nothing if we're not dragging.
    If m_DraggingMarker < 0 Then Exit Sub

    ' Position the marker.
    lblTab(m_DraggingMarker).Left = _
        lblTab(m_DraggingMarker).Left + _
        (X - m_StartX)
End Sub

' Finish dragging the tab marker.
Private Sub lblTab_MouseUp(Index As Integer, Button As _
    Integer, Shift As Integer, X As Single, Y As Single)
    ' Do nothing if we're not dragging.
    If m_DraggingMarker < 0 Then Exit Sub
    m_DraggingMarker = -1

    ' Set the tabs.
    SetTabs
End Sub
 
The SetTabs subroutine loads the positions of the tab marker controls into an array. It then calls the Quicksort subroutine to sort the tab positions. See the HowTo Sort a list using quicksort for details.

SetTabs then uses the RichTextBox's SelStart and SelLength properties to select all of the text. It sets the control's SelTabCount property to determine the number of tabs. It then uses the SelTabs method to set the tabs.

 
' Set the tabs based on the locations
' of the tab markers.
Private Sub SetTabs()
Dim max_tab As Integer
Dim i As Integer
Dim tabs() As Single
Dim sel_start As Long
Dim sel_length As Long

    ' Make an array of the tab positions.
    max_tab = lblTab.UBound
    ReDim tabs(0 To max_tab)
    For i = 0 To max_tab
        tabs(i) = lblTab(i).Left - RichTextBox1.Left + _
            lblTab(i).Width
    Next i

    ' Sort the tabs.
    Quicksort tabs, 0, max_tab

    ' Select all the text and specify
    ' the number of tabs.
    sel_start = RichTextBox1.SelStart
    sel_length = RichTextBox1.SelLength
    RichTextBox1.SelStart = 0
    RichTextBox1.SelLength = Len(RichTextBox1.Text)
    RichTextBox1.SelTabCount = max_tab + 1

    ' Define the tabs.
    For i = 0 To max_tab
        RichTextBox1.SelTabs(i) = tabs(i)
    Next i

    RichTextBox1.SelStart = sel_start
    RichTextBox1.SelLength = sel_length
End Sub
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated