Visual Basic Reference

ActiveControl Property Example

This example displays the text of the active control. To try this example, paste the code into the Declarations section of a form that contains TextBox, Label, and CommandButton controls, and then press F5 and click the form.

  Private Sub Form_Click ()
   If TypeOf Screen.ActiveControl Is TextBox Then
      Label1.Caption = Screen.ActiveControl.Text
   Else
      Label1.Caption = "Button: " + Screen.ActiveControl.Caption
   End If
End Sub

This example shows how you can use the Clipboard object in cut, copy, paste, and delete operations using buttons on a toolbar. To try this example, put TextBox and CheckBox controls on Form1, and then create a new MDI form. On the MDI form, insert a PictureBox control, and then insert a CommandButton in the PictureBox. Set the Index property of the CommandButton to 0 (creating a control array). Set the MDIChild property of Form1 to True.

To run the example, copy the code into the Declarations section of the MDIForm, and then press F5. Notice that when the CheckBox has the focus, the buttons don't work, since the CheckBox is now the active control instead of the TextBox.

  Private Sub MDIForm_Load ()
   Dim I   ' Declare variable.
   Command1(0).Move 0, 0, 700, 300   ' Position button on toolbar.
   For I = 1 To 3   ' Create other buttons.
      Load Command1(I)   ' Create button.
      Command1(I).Move I * 700, 0, 700, 300  ' Place and size button.
      Command1(I).Visible = True   ' Display button.
   Next I
   Command1(0).Caption = "Cut"   ' Set button captions.
   Command1(1).Caption = "Copy"
   Command1(2).Caption = "Paste"
   Command1(3).Caption = "Del"
End Sub

Private Sub Command1_Click (Index As Integer)
   ' ActiveForm refers to the active form in the MDI form.
   If TypeOf ActiveForm.ActiveControl Is TextBox Then
      Select Case Index
         Case 0   ' Cut.
            ' Copy selected text onto Clipboard.
            Clipboard.SetText ActiveForm.ActiveControl.SelText
            ' Delete selected text.
            ActiveForm.ActiveControl.SelText = ""
         Case 1   ' Copy.
            ' Copy selected text onto Clipboard.
            Clipboard.SetText ActiveForm.ActiveControl.SelText
         Case 2   ' Paste.
            ' Put Clipboard text in text box.
            ActiveForm.ActiveControl.SelText = Clipboard.GetText()
         Case 3   ' Delete.
            ' Delete selected text.
            ActiveForm.ActiveControl.SelText = ""
      End Select
   End If
End Sub