All TextBoxes and ComboBoxes have a set of properties for selected text. They are:
Property | Description |
SelStart | An integer that equals the starting position of the selected block of text. If no text is selected, it equals the position of the cursor. |
SelLength | An integer that equals the number of characters selected. |
SelText | A string containing the selected characters (or an empty string [e.g., ""] if no characters are selected). |
You can control what text is selected by setting the SelStart and SelLength properties. For example:
TxtInput.SetFocus ' Sets txtInput to have the focus TxtInput.SelStart = 0 ' Starting at the beginning of the text TxtInput.SelLength = Len(Text1.Text) ' Select everything
If you assign a new string to SelText, that string replaces the selected text, and the cursor is placed just after the newly inserted text.
Visual Basic has a Clipboard object, which has a SetText function to which you can send data, and a GetText function from which you can receive data (from the clipboard). It also includes a Clear function, which erases all the data in the clipboard. Here's a good example of the code for the Cut, Copy, and Paste menus in all Windows programs (using whatever control happens to be active, referenced with a special variable named Screen.ActiveControl):
Private Sub mnuCut_Click () Clipboard.Clear Clipboard.SetText Screen.ActiveControl.SelText Screen.ActiveControl.SelText = "" End Sub Private Sub mnuCopy_Click () Clipboard.Clear Clipboard.SetText Screen.ActiveControl.SelText End Sub Private Sub mnuPaste_Click () Screen.ActiveControl.SelText = Clipboard.GetText() End Sub
Note that you can't copy, for example, a picture to the clipboard this way. However, you can if you use the following code (this time, just using the Copy command as an example):
Private Sub mnuCopy_Click () Clipboard.Clear If TypeOf Screen.ActiveControl Is TextBox Then Clipboard.SetText Screen.ActiveControl.SelText ElseIf TypeOf Screen.ActiveControl Is ComboBox Then Clipboard.SetText Screen.ActiveControl.Text ElseIf TypeOf Screen.ActiveControl Is PictureBox Then Clipboard.SetText Screen.ActiveControl.Picture ElseIf TypeOf Screen.ActiveControl Is ListBox Then Clipboard.SetText Screen.ActiveControl.Text End If ' Note that no action makes sense for any other control End Sub