JavaScript Editor JavaScript Editor     JavaScript Debugger

Previous Section Next Section

Main Page

Copying or Getting Selected Text to or from the Clipboard

After entering their new novels into your program, users were surprised that they couldn't copy them to the clipboard and so paste them into other applications. How can you support the clipboard with text in a text box? You can use the Clipboard object's SetDataObject and GetDataObject class methods. Here's an example, which is called Clipboard on the CD-ROM. In this case, I'm placing the selected text from one text box into the clipboard when the user clicks a button, and putting it into another text box when the user clicks another. The call to SetDataObject places the data in the clipboard; GetDataObject gets the data from the clipboard; you can check if it is text data with the GetDataPresent method and the DataFormats enumeration's Text item; and you get the actual data with GetData:

Public Class Form1
    Inherits System.Windows.Forms.Form

    'Windows Form Designer generated code

    Private Sub Button1_Click(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles Button1.Click
        System.Windows.Forms.Clipboard.SetDataObject_
            (TextBox1.SelectedText)
    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles Button2.Click
        Dim ClipboardData As System.Windows.Forms.IDataObject = _
            System.Windows.Forms.Clipboard.GetDataObject()
        If ClipboardData.GetDataPresent(DataFormats.Text) Then
            TextBox2.Text = ClipboardData.GetData(DataFormats.Text)
        End If
    End Sub
End Class

You can see this example at work in Figure 5.5.


Figure 5.5: Using the clipboard.

This example shows how to use the clipboard in a general way, but in fact, there's an easier way to do this with text boxes to handle selected text-you can use the TextBox class's Copy, Cut, and Paste methods.

Tip 

Text boxes already allow the user to use these shortcuts to work with the clipboard: Ctrl+C to copy selected text, Ctrl+V to paste text from the clipboard, and Ctrl+X to cut selected text.

Previous Section Next Section




JavaScript Editor Free JavaScript Editor     JavaScript Editor