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: |
Click here to copy the following block | Sub PasteIntoTextBox(ByVal tb As TextBox) Dim data As IDataObject = Clipboard.GetDataObject If data.GetDataPresent(DataFormats.Text, True) Then 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): |
Click here to copy the following block | Sub PasteIntoRichTextBox(ByVal rtf As RichTextBox) Dim data As IDataObject = Clipboard.GetDataObject
If data.GetDataPresent(DataFormats.Rtf, False) Then rtf.SelectedRtf = data.GetData(DataFormats.Rtf).ToString ElseIf data.GetDataPresent(DataFormats.Text, True) Then rtf.SelectedText = data.GetData(DataFormats.Text, True).ToString End If End Sub |
|