Step 7: Clipboard Support

The Windows clipboard is a very useful device for transferring information between applications. Adding clipboard support to VSFlexGrid projects is very easy. All it takes is the following code:

Private Sub fg_KeyDown(KeyCode%, Shift%)

    Dim Cpy As Boolean, Pst As Boolean

    ' copy: CTRL-C, CTRL-X, CTRL-INS

    If KeyCode = vbKeyC And Shift = 2 Then Cpy = True

    If KeyCode = vbKeyX And Shift = 2 Then Cpy = True

    If KeyCode = vbKeyInsert And Shift = 2 Then Cpy = True

   

    ' paste: CTRL-V, SHIFT-INS

    If KeyCode = vbKeyV And Shift = 2 Then Pst = True

    If KeyCode = vbKeyInsert And Shift = 1 Then Pst = True

    ' do it

    If Cpy Then

        Clipboard.Clear

        Clipboard.SetText fg.Clip

    ElseIf Pst Then

        fg.Clip = Clipboard.GetText

    End If

End Sub

The routine handles all standard keyboard commands related to the clipboard: CTRL-X, CTRL-C, or CTRL-INSERT to copy, and CTRL-V or SHIFT-INSERT to paste. The real work is done by the Clip property, which takes care of copying and pasting the clipboard text over the current range.

Another great Windows feature that is closely related to clipboard operations is OLE Drag and Drop. VSFlexGrid has two properties, OLEDragMode and OLEDropMode, that help implement this feature. Just set both properties to their automatic settings and you will be able to drag selections by their edges and drop them into other applications such as Microsoft Excel, or drag ranges from an Excel spreadsheet and drop them into the VSFlexGrid control.

Press F5 to run the project again, then try copying and pasting some data. You will notice that it is possible to paste invalid data, because our paste code does not do any data validation. This is left as an exercise for the reader.