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

2

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

vb.net
clipboarddata
asked on Stack Overflow Sep 15, 2014 by Eric • edited Jun 20, 2020 by Community

3 Answers

4

You could use directly My.Computer.FileSystem.CopyFile.

Dim source As String = lvFotos.SelectedItems(0).Tag
Dim destination As String = My.Computer.FileSystem.SpecialDirectories.Desktop & from.Substring(from.LastIndexOf("\"))
My.Computer.FileSystem.CopyFile(source, destination)
answered on Stack Overflow Sep 15, 2014 by Francesco Menzani
2

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.

answered on Stack Overflow Sep 15, 2014 by Andrew Morton • edited Sep 16, 2014 by Andrew Morton
1

Found what I was doing wrong.

At first I had tried it with the name of the file in an array, but that gave the same error.

Now I have it like this:

 Dim selectedfile(0) As String

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

Dim dataobj As New DataObject

dataobj.SetData(DataFormats.FileDrop, True, selectedfile)

Clipboard.Clear()
Clipboard.SetDataObject(dataobj, True)

The difference is in the line with SETDATA. By setting the second argument to TRUE in SetData and also in the SetDataObject, it started to work.

answered on Stack Overflow Sep 16, 2014 by Eric • edited May 4, 2015 by Francesco Menzani

User contributions licensed under CC BY-SA 3.0