Search code examples
vb.netclipboarddata

How do I copy a file to the clipboard and paste it somewhere else?


I have a listview with small thumbnails of images. Each image has a tag with it's full path in it.

With a rightclick menu the user can click COPY.

Then this code is excecuted:

Dim selectedfile As String

selectedfile = Me.lvFotos.SelectedItems(0).Tag


Dim dataobj As New DataObject(DataFormats.FileDrop, selectedfile)

Clipboard.Clear()
Clipboard.SetDataObject(dataobj)

Now when I click on my desktop to paste the file I get an exception error in VS2010:

An exception of type 'System.Runtime.InteropServices.COMException' occurred in System.Windows.Forms.dll and wasn't handled before a managed/native boundary

Additional information: Invalid FORMATETC structure (Exception from HRESULT: 0x80040064 (DV_E_FORMATETC))

What am I doing wrong here?

rg. Eric


Solution

  • Using the code from John Smith at Copying a File To The Clipboard:

    Dim f() As String = {"C:\temp\Folder.jpg"}
    Dim d As New DataObject(DataFormats.FileDrop, f)
    Clipboard.SetDataObject(d, True)
    

    (Tested as working in VS2013 on Windows 7 x64.)

    Note that you have to pass an array of strings representing your filename(s), so you could allow the user to gather several items before pasting, if you wanted to.

    The true in Clipboard.SetDataObject allows the data to remain on the clipboard when you exit the program, so if the user were to select a file and exit before pasting, they would not have lost their selection.