Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: VBNET
Expertise: Intermediate
Feb 3, 2002

Pasting data from the Clipboard

Pasting data from the clipboard requires more code because you must ascertain whether the clipboard contains data in one of the formats you're willing to process. First, use the Clipboard.GetDataObject to retrieve an IDataObject object. Next, use the GetDataPresent method of this IDataObject object to determine whether the clipboard contains data in the format specified by the first argument. If the second argument is True or omitted, the method attempts to force the conversion to the specified format. (For example, it might try to force the conversion from RTF text to plain text.) If the GetDataPresent method returns True, you can extract the actual value with the GetData method. The following routine attempts to paste the current contents of the clipboard into a TextBox control:

Sub PasteIntoTextBox(ByVal tb As TextBox)
    ' Get the data currently in the clipboard.
    Dim data As IDataObject = Clipboard.GetDataObject
    ' Check if there is any data in text format, converting it if necessary.
    If data.GetDataPresent(DataFormats.Text, True) Then
        ' If yes, paste into the selection.
        tb.SelectedText = data.GetData(DataFormats.Text, True).ToString
    End If
End Sub
Depending on the type of the target controls, you might need to make multiple attempts before you find a matching format. For example, this procedure attempts a paste operation into a RichTextBox control. Note that you need to start by testing the richest format (RTF, in this case), without attempting a conversion, and then continue with less rich formats (plain text, in this case):

Sub PasteIntoRichTextBox(ByVal rtf As RichTextBox)
    ' Get the data currently in the clipboard.
    Dim data As IDataObject = Clipboard.GetDataObject

    ' Check if there is any data in RTF format, 
    ' WITHOUT attempting a conversion.
    If data.GetDataPresent(DataFormats.Rtf, False) Then
        ' If available, paste into the RTF selection.
        rtf.SelectedRtf = data.GetData(DataFormats.Rtf).ToString
    ElseIf data.GetDataPresent(DataFormats.Text, True) Then
        ' Else, attempt to get data in plain text format.
        rtf.SelectedText = data.GetData(DataFormats.Text, True).ToString
    End If
End Sub
Francesco Balena
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date