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 IfEnd 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 IfEnd Sub

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: