TX Text Control ActiveX

Selections, Clipboard and Undo

Topic

Which text does a menu command work on, and how does the user take it back? In TXTextControl, commands work on the selection, the highlighted text, or on the input position, the place where the caret stands when nothing is selected. Cut, copy and paste move the selection through the clipboard, and the undo buffer records each edit so that it can be undone and redone.

The Visual Basic 6 code below comes from the Edit menu of the TXWords sample, which A Word Processor describes, and from the reference. It selects and replaces text in code, runs the clipboard commands, enables menu items, undoes edits and groups them, searches the text and switches between inserting and overwriting.

Select Text in Code

Three run-time properties describe the selection:

  • SelStart is the zero-based position where the selection starts, or the input position when no text is selected. A value greater than the text length is limited to the text length, and -1 sets the start to the end of the document.
  • SelLength is the number of selected characters, from 0 to the text length. A value larger than the text extends the selection to the end of the document.
  • SelText is the selected text as a plain string, or an empty string when nothing is selected. Setting it replaces the selection with the new string and sets SelLength to 0.

The following code selects the first five characters, reads them and replaces them:

Dim OldText As String

' Select characters 0 to 4
TXTextControl1.SelStart = 0
TXTextControl1.SelLength = 5
OldText = TXTextControl1.SelText

' Replace the selection with new text
TXTextControl1.SelText = "Hello"

SelText holds text without formatting. RTFSelText works the same way on the selection that SelStart and SelLength set, but reads and writes it as an RTF string with all formatting attributes.

Select All Text

The Select All command of the TXWords Edit menu (CTRL+A) selects the whole document from position 0:

Private Sub mnuEdit_SelectAll_Click()
    TXTextControl1.SelStart = 0
    TXTextControl1.SelLength = -1
End Sub

TXWords sets SelLength to -1 here. The reference documents the other way to reach the end of the document: a SelLength larger than the text extends the selection to its end.

Keep the Selection Visible

By default, the selection is hidden when TXTextControl loses the input focus, for instance to a dialog box of your application, and shown again when the control gets the focus back. Set HideSelection to False to keep it visible:

TXTextControl1.HideSelection = False

Format the Selection

Formatting properties such as FontBold apply to the complete text by default. Set FormatSelection to True, as TXWords does when its main form loads, to make them apply to the selected text only. Character and Paragraph Formatting covers the formatting properties.

Work With the Input Position

The input position is a character position, but you can also read and set it as a page, a line and a column. CurrentInputPosition is an array of three Long values, the numbers that the status bar shows. Each of them starts at 1:

Dim cur As Variant

' Get the current page, line and column
cur = TXTextControl1.CurrentInputPosition
MsgBox "Page " & cur(0) & ", line " & cur(1) & ", column " & cur(2)

' Move the input position to the start of the text
cur(0) = 1 ' page
cur(1) = 1 ' line
cur(2) = 1 ' column
TXTextControl1.CurrentInputPosition = cur

To find the input position at a point of the control, call InputPosFromPoint with the coordinates of the point in twips, 1/1440 inch, which Text Formatting and Views explains. The method returns the zero-based input position, or -1 if there is no text position at that point. TXWords places the input position where a file is dropped this way:

frmMain.TXTextControl1.SelStart = frmMain.TXTextControl1.InputPosFromPoint(X, Y)

The PosChange event occurs whenever the input position changes. TXWords uses it to enable and disable its toolbar buttons, as the next section shows.

Cut, Copy and Paste

One method runs all clipboard commands: Clip, with the action as its parameter. TXWords declares a constant for each action in its module tx.bas:

ValueTXWords constantAction
1CLIP_CUTCuts out the selected text and copies it to the clipboard.
2CLIP_COPYCopies the selected text to the clipboard.
3CLIP_PASTEPastes text from the clipboard.
4CLIP_CLEARClears the selection.

The Cut, Copy, Paste and Delete commands of the TXWords Edit menu each call Clip:

Private Sub mnuEdit_Cut_Click()
    TXTextControl1.Clip CLIP_CUT
End Sub

Private Sub mnuEdit_Copy_Click()
    TXTextControl1.Clip CLIP_COPY
End Sub

Private Sub mnuEdit_Paste_Click()
    TXTextControl1.Clip CLIP_PASTE
End Sub

Private Sub mnuEdit_Delete_Click()
    TXTextControl1.Clip CLIP_CLEAR
End Sub

Enable the Clipboard Commands

A clipboard command makes sense only when there is something to cut, copy or paste. Two read-only properties tell you:

  • CanCopy is True when part of the document is selected and can be copied.
  • CanPaste is True when the clipboard holds a format that can be pasted into the document.

TXWords checks both each time the input position changes and enables its toolbar buttons accordingly. Cutting also needs CanEdit, which is True when the text at the input position can be changed; in a protected document it can be False:

Private Sub TXTextControl1_PosChange()
    With Toolbar1
       .Buttons("Cut").Enabled = TXTextControl1.CanCopy And TXTextControl1.CanEdit
       .Buttons("Copy").Enabled = TXTextControl1.CanCopy
       .Buttons("Paste").Enabled = TXTextControl1.CanPaste
    End With
End Sub

TXWords calls a procedure named EnableToolbarButtons from the PosChange event, which enables more buttons than this excerpt. Document Protection explains the edit modes and permissions behind CanEdit.

Undo and Redo

The undo buffer of TXTextControl records the edits of the user and of your code. The Undo method undoes the last operation and Redo redoes it. Both return True when they succeed. The keys CTRL+Z and CTRL+Y do the same for the user.

Private Sub mnuEdit_Undo_Click()
    TXTextControl1.Undo
End Sub

Private Sub mnuEdit_Redo_Click()
    TXTextControl1.Redo
End Sub

Name the Operation in the Menu

CanUndo and CanRedo return 0 when there is nothing to undo or redo. Otherwise they return a number that identifies the operation, such as 1 for inserted text, 19 for an inserted image or 23 for an inserted table; the reference pages list all numbers. For inserted, deleted and formatted text, the two properties use different numbers: CanUndo returns 1, 2 and 3, CanRedo returns 10, 11 and 12.

TXWords turns the number into a menu caption such as "Undo insert text" with the functions UndoActionName and RedoActionName of tx.bas, and it disables the commands when the number is 0. It does this in the Click event of the Edit menu, which occurs when the user opens the menu:

Private Sub mnuEdit_Click()
    Dim UndoState As Integer
    Dim RedoState As Integer

    With TXTextControl1
        UndoState = .CanUndo
        RedoState = .CanRedo

        mnuEdit_Undo.Caption = UndoActionName(UndoState)
        mnuEdit_Redo.Caption = RedoActionName(RedoState)

        mnuEdit_Undo.Enabled = (UndoState <> 0)
        mnuEdit_Redo.Enabled = (RedoState <> 0)

        mnuEdit_Cut.Enabled = .CanCopy And .CanEdit
        mnuEdit_Copy.Enabled = .CanCopy
        mnuEdit_Paste.Enabled = .CanPaste
    End With
End Sub

The TXWords Edit menu of an unchanged document, with the captions Nothing to undo and Nothing to redo and the disabled Cut, Copy and Paste items.

Group Several Changes Into One Undo Step

When your code changes the document with several property and method calls, the user would have to undo each of them separately. StartUndoAction and EndUndoAction define a single undo action: all calls between them are undone in one step.

With TXTextControl1
    .FormatSelection = True

    .StartUndoAction
    ' Insert a greeting at the start of the text
    .SelStart = 0
    .SelLength = 0
    .SelText = "Dear Customer"
    ' Make it bold
    .SelStart = 0
    .SelLength = Len("Dear Customer")
    .FontBold = 1
    .EndUndoAction
End With

After this code runs, one Undo removes both the inserted text and its bold formatting.

Switch the Undo Buffer Off

AllowUndo switches the undo buffer on and off. It is on by default, and off by default when the control runs on a server. When you use a TXTextControl to generate reports, switching it off saves time and memory. TXWords switches it off while its main form sets up the control and on again afterward:

TXTextControl1.AllowUndo = False ' Disable undo buffer

' Set options
TXTextControl1.ScrollBars = 3 ' Both horizontal and vertical
TXTextControl1.FormatSelection = True ' Formatting options only apply to selected text

TXTextControl1.AllowUndo = True ' Enable undo buffer

Search the Text

The Find method searches the document for a string. It returns the zero-based position of the match and highlights it, or returns -1 when the string is not found. The optional second parameter is the position to start at; when you omit it or pass -1, the search starts at the input position. The optional third parameter is the sum of these options:

ValueOptionEffect
1SearchUpSearches up instead of down.
4MatchCaseMatches the case of the string as well.
8NoHighLightControls whether the match is highlighted.
16NoMessageBoxSuppresses the built-in message box that says a match could not be found.
64MatchWholeWordFinds whole words only.

The following code searches the whole document for the whole word "invoice", with matching case and without a message box:

Dim Pos As Long

Pos = TXTextControl1.Find("invoice", 0, 4 + 16 + 64)
If Pos = -1 Then
    MsgBox "The word was not found."
End If

For a search and replace dialog box, you don't need code of your own. The Find and Replace commands of TXWords call FindReplace with 1 or 2, and TXTextControl opens its built-in dialog box; A Word Processor shows it.

The built-in Find dialog box of TXTextControl with the Find what box, the options Match case, Match whole word only and Search up, and the parts of the document to search in.

The built-in Replace dialog box of TXTextControl with the Find what and Replace with boxes, the same find options and the buttons Find Next, Replace and Replace All.

Switch Between Insert and Overwrite

InsertionMode decides whether typed text is inserted, the default (True), or overwrites the existing text (False). TXWords toggles it with the INSERT key in the KeyDown event:

Private Sub TXTextControl1_KeyDown(KeyCode As Integer, Shift As Integer)
    If KeyCode = vbKeyInsert And Shift = 0 Then
        TXTextControl1.InsertionMode = Not TXTextControl1.InsertionMode
    End If
End Sub

The KeyStateChange event occurs when the insertion mode or the state of the NUMLOCK or CAPSLOCK key changes.

Use the Built-In Mouse and Keyboard Interface

Users select, edit and move text without any code of yours. A double-click selects a word, a triple-click a paragraph, and SHIFT + click extends the selection to the point of the click. Dragging selected text moves it, and dragging it with CTRL pressed copies it. SHIFT together with a key that moves the caret, such as SHIFT + END, extends the selection to the new caret position.

Mouse Assignment and Keyboard Assignment list every mouse action and key and what the control does. For your own reactions to the mouse and the keyboard, TXTextControl raises the events of the programming category Text Selections and Character Input, such as MouseDown, MouseUp, KeyDown and KeyPress.

Key Members

MemberDescription
SelStartThe zero-based start of the selection, or the input position.
SelLengthThe number of selected characters.
SelTextThe selected text; setting it replaces the selection.
CurrentInputPositionThe page, line and column of the input position.
InputPosFromPointReturns the input position at a point given in twips.
PosChangeOccurs when the input position changes.
ClipCuts, copies, pastes or clears the selection.
CanCopyTells whether text is selected and can be copied.
CanPasteTells whether the clipboard holds a format that can be pasted.
UndoUndoes the last operation.
RedoRedoes the last undone operation.
CanUndoReturns the operation that Undo can undo, or 0.
CanRedoReturns the operation that Redo can redo, or 0.
StartUndoActionStarts a group of calls that are undone in one step.
EndUndoActionEnds the group that StartUndoAction started.
AllowUndoSwitches the undo buffer on or off.
FindSearches the document for a string.
InsertionModeSwitches between inserting and overwriting text.