Jump to content

Sky Slate Blueberry Blackcurrant Watermelon Strawberry Orange Banana Apple Emerald Chocolate

how to copy a file to the clipboard


  • Please log in to reply
58 replies to this topic
maraskan_user
  • Members
  • 52 posts
  • Last active: Dec 08 2014 11:18 PM
  • Joined: 20 Jun 2008

Does FileToClipboard(PathToCopy) also work with multiple files selected at once and all of them are copied into the clipboard.


Yes. FileToClipboard in both the simpler and the extended version accepts `n-separated pathlists.

How would be an example if I would want to copy all .bla files from a given directory into the clipboard?


Like this? It produces a variable with your pathlist through a loop and then hands it to the function.

CopyFilePath=
loop,c:\MyDirectory\*.bla,0,1
	{
	CopyFilePath:= A_LoopFileFullPath "`n" CopyFilePath
	}
FileToClipboard(CopyFilePath,"copy")
return

Can the method be also "paste"?


Nope. It just makes the specified files readily pasteable, by putting a list into the clipboard, like pressing Ctrl+C for copy and Ctrl+X for cut basically also does. You can then past into explorer windows just like you normally would. Depending on whether you marked the files for copy or cut, explorer will either leave the source files in place or delete them after the copy operation.

Copy and paste is usually done in different folders/windows, so it's split up in two separate actions, so you can switch to your target inbetween. Making it a one step process, you would either be unable to specify your source, or your target.

Maybe what you are trying to do is something like marking files in explorer, and then using a hotkey to move or copy them to a folders you specify in advance? This could work like this, maybe:

#1::
pp_ClipTemp=%ClipboardAll%
Clipboard =
SendInput,^c
ClipWait,2
File=%Clipboard%
Clipboard=%pp_ClipTemp%
Loop,Parse,File,`n,`r
   {
   TargetFile:=A_LoopField
   SplitPath,LoopField,FName,FDir,FExt,FNameNoExt,
   FileCopy,%LoopField%,c:\DifferentFolder\%FNameNoExt%.%FExt%, Flag]
   }
return


automaticman
  • Members
  • 658 posts
  • Last active: Nov 20 2012 06:10 PM
  • Joined: 27 Oct 2006
Thanks maraskan_user for your detailed reply, yesterday just after asking my question I could see that it works nicely also with multiple file paths in a PathList.

Now what I am trying to figure out is what the difference between normal pasting (control-v) and control-drag'n'drop is. My goal is to replace the control-drag'n'drop action of a PathList with internal AHK-solution which ends in the same result but without requiring any mouse or drag'n'drop interaction. Do you have any ideas or tips how we can simulate a control-drag'n'drop event using a given PathList?

maraskan_user
  • Members
  • 52 posts
  • Last active: Dec 08 2014 11:18 PM
  • Joined: 20 Jun 2008

Thanks maraskan_user for your detailed reply, yesterday just after asking my question I could see that it works nicely also with multiple file paths in a PathList.

Now what I am trying to figure out is what the difference between normal pasting (control-v) and control-drag'n'drop is. My goal is to replace the control-drag'n'drop action of a PathList with internal AHK-solution which ends in the same result but without requiring any mouse or drag'n'drop interaction. Do you have any ideas or tips how we can simulate a control-drag'n'drop event using a given PathList?


Try ClipSpy (http://www.softpedia...oad-127033.html) if you want to find out what exactly is on the clipboard if you do different things. Try it with ctrl+c and with dragging and dropping a file into the left panel of ClipSpy.
I don't think drag and drop can be simulated atm. Even if you fill the clipboard with exactly the same stuff as ClipSpy shows, there might still be something missing, which might also be the reason why nobody has gotten Drag'n'Drop out of Gui ListViews to work.

lab01
  • Members
  • 2 posts
  • Last active: Nov 01 2009 09:54 AM
  • Joined: 30 Oct 2009
Hello, I read the whole post but couldn't find an answer to my question, that is: How to copy to the clipboard the name ,without its path and without its extension, of a single selected file (or folder) in windows explorer?
I know that this

Clipboard =
Send ^c
ClipWait 2
if ErrorLevel
    return
Sort Clipboard
return

will do the job but will include the full path of what's selected (including the extension, if I selected a file)..
I read somewhere that I should insert in the code the SplithPath command, maybe something like SplitPath, FullFileName, name_no_ext...
Thanks for your time,

Cheers

p.s. atm I'm using a "rough" way,

Send {F2}
sleep 50
Send ^c
sleep 50
Send {Enter}
return


SoLong&Thx4AllTheFish
  • Members
  • 4999 posts
  • Last active:
  • Joined: 27 May 2007
Example on how to get filename without extension from clipboard
Clipboard = C:\My Documents\Address List.txt ; replace with Send ^c

SplitPath, Clipboard, , , , name_no_ext

MsgBox % name_no_ext
See splitpath help for more

Scratch
  • Members
  • 108 posts
  • Last active: Mar 16 2014 08:02 PM
  • Joined: 22 Jan 2009
This might not be exactly what you are looking for, but you could paste AHK vars, including %clipboard% into a mssearch index file and run that

!F::
FileDelete custom.search-ms
inputbox AHKsearchext, File Extension e.g JPG ?

Fileappend,
(
<?xml version="1.0"?>
<persistedQuery version="1.0"><viewInfo iconSize="32" stackIconSize="0" displayName="Search Results in Computer" autoListFlags="0"><visibleColumns><column viewField="System.ItemNameDisplay"/><column viewField="System.DateModified"/><column viewField="System.ItemTypeText"/><column viewField="System.Size"/><column viewField="System.ItemFolderPathDisplayNarrow"/></visibleColumns><sortList><sort viewField="System.Search.Rank" direction="descending"/><sort viewField="System.DateModified" direction="descending"/><sort viewField="System.ItemNameDisplay" direction="ascending"/></sortList></viewInfo><query><conditions><condition type="leafCondition" property="System.FileExtension" operator="starts with" propertyType="string" value=".%AHKsearchext%" localeName="en-US"><attributes><attribute attributeID="{9554087B-CEB6-45AB-99FF-50E8428E860D}" clsid="{C64B9B66-E53D-4C56-B9AE-FEDE4EE95DB1}" chs="1" sqro="585" timestamp_low="2725415300" timestamp_high="30038825"><condition type="leafCondition" property="System.FileExtension" operator="starts with" propertyType="string" value=".%AHKsearchext%" localeName="en-US"><attributes><attribute attributeID="{9554087B-CEB6-45AB-99FF-50E8428E860D}" clsid="{C64B9B66-E53D-4C56-B9AE-FEDE4EE95DB1}" chs="1" sqro="585" timestamp_low="2154252800" timestamp_high="30038825"><condition type="leafCondition" property="" operator="imp" propertyType="string" value="*.%AHKsearchext%
0000 0000 0000 0001 0002 0003 N F" valuetype="System.StructuredQueryType.FilePath" localeName="en-US"><attributes><attribute attributeID="{9554087B-CEB6-45AB-99FF-50E8428E860D}" clsid="{C64B9B66-E53D-4C56-B9AE-FEDE4EE95DB1}" chs="0" parsedString="*.%AHKsearchext%" localeName="en-US" timestamp_low="2154252800" timestamp_high="30038825"/></attributes></condition></attribute></attributes></condition></attribute></attributes></condition></conditions><kindList><kind name="item"/></kindList><scope><include knownFolder="{0AC0837C-BBF8-452A-850D-79D08E667CA7}"/></scope></query><properties><author Type="string">7</author></properties></persistedQuery>
), custom.search-ms
Run custom.search-ms
;
; View list mode (without pathnames)
sleep 300
send {F10}!vl
return


lab01
  • Members
  • 2 posts
  • Last active: Nov 01 2009 09:54 AM
  • Joined: 30 Oct 2009
Thank you both for the help, really appreciated :)
This is the code I needed:

clipboard =
Send, ^c
ClipWait, 2
Sort, clipboard
SplitPath, Clipboard, , , , name_no_ext
clipboard = % name_no_ext
return


Cheers

fragman
  • Members
  • 1591 posts
  • Last active: Nov 12 2012 08:51 PM
  • Joined: 13 Oct 2009
Here are 2 functions for copying Unicode files to the clipboard based on the function originally posted by Lexikos here. Those functions should be used on Unicode builds of Autohotkey_L, and they accept filepaths separated by new lines. There's also lots of comments explaining what is done for anyone interested.

;Copies a list of files (separated by new line) to the clipboard so they can be pasted in explorer
/* Example clipboard data:
00000000   14 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00    ................
00000010   01 00 00 00 43 00 3A 00 5C 00 62 00 6F 00 6F 00    ....C.:.\.b.o.o.				<-- I believe the 01 byte at the start of this line could indicate unicode?
00000020   74 00 6D 00 67 00 72 00 00 00 43 00 3A 00 5C 00    t.m.g.r...C.:.\.
00000030   62 00 6C 00 61 00 2E 00 6C 00 6F 00 67 00 00 00    b.l.a...l.o.g...
00000040   00 00                                             										..     

typedef struct _DROPFILES {
  DWORD pFiles;
  POINT pt;
  BOOL  fNC;
  BOOL  fWide;
} DROPFILES, *LPDROPFILES;

_DROPFILES struct: 20 characters at the start
null-terminated filename list, and double-null termination at the end
*/
CopyToClipboard(files, clear, cut=0){
	global CF_HDROP
	FileCount:=0
	PathLength:=0
	;Count files and total string length
	Loop, Parse, files, `n,`r  ; Rows are delimited by linefeeds (`r`n).
	{
		FileCount++
		PathLength+=StrLen(A_LoopField)
	}
	pid:=DllCall("GetCurrentProcessId","Uint")
	hwnd:=WinExist("ahk_pid " . pid)
	DllCall("OpenClipboard", "Ptr", hwnd)
	hPath := DllCall("GlobalAlloc", "uint", 0x42, "uint", 20 + (PathLength + FileCount + 1) * 2, "Ptr")      ; 0x42 = GMEM_MOVEABLE(0x2) | GMEM_ZEROINIT(0x40)
	pPath := DllCall("GlobalLock", "Ptr", hPath)                   ; Lock the moveable memory, retrieving a pointer to it.
	NumPut(20, pPath+0), pPath += 16 ; DROPFILES.pFiles = offset of file list
	NumPut(1, pPath+0), pPath += 4 ;fWide = 0 -->ANSI, fWide = 1 -->Unicode
	Offset:=0
	Loop, Parse, files, `n,`r  ; Rows are delimited by linefeeds (`r`n).
		offset += StrPut(A_LoopField, pPath+offset,StrLen(A_LoopField)+1,"UTF-16") * 2
	DllCall("GlobalUnlock", "Ptr", hPath)  
	;hPath must not be freed! ->http://msdn.microsoft.com/en-us/library/ms649051(VS.85).aspx
	if clear
	{
		DllCall("EmptyClipboard")                                                              ; Empty the clipboard, otherwise SetClipboardData may fail.
		Clipwait, 1, 1
	}
	result:=DllCall("SetClipboardData", "uint", CF_HDROP, "Ptr", hPath) ; Place the data on the clipboard. CF_HDROP=0xF
	Clipwait, 1, 1
	
	;Write Preferred DropEffect structure to clipboard to switch between copy/cut operations
 	mem := DllCall("GlobalAlloc","UInt",0x42,"UInt",4, "Ptr")  ; 0x42 = GMEM_MOVEABLE(0x2) | GMEM_ZEROINIT(0x40)
	str := DllCall("GlobalLock","Ptr",mem) 
	if(!cut)
		DllCall("RtlFillMemory","UInt",str,"UInt",1,"UChar",0x05) 
	else 
		DllCall("RtlFillMemory","UInt",str,"UInt",1,"UChar",0x02) 
	DllCall("GlobalUnlock","Ptr",mem)
	cfFormat := DllCall("RegisterClipboardFormat","Str","Preferred DropEffect") 
	result:=DllCall("SetClipboardData","UInt",cfFormat,"Ptr",mem)
	Clipwait, 1, 1
	DllCall("CloseClipboard")
	;mem must not be freed! ->http://msdn.microsoft.com/en-us/library/ms649051(VS.85).aspx
	return
}

;Appends files to CF_HDROP structure in clipboard
AppendToClipboard( files, cut=0) { 
	DllCall("OpenClipboard", "Ptr", 0)
	if(DllCall("IsClipboardFormatAvailable", "Uint", 1)) ;If text is stored in clipboard, clear it and consider it empty (even though the clipboard may contain CF_HDROP due to text being copied to a temp file for pasting)
		DllCall("EmptyClipboard")
	DllCall("CloseClipboard")
	txt:=clipboard (clipboard = "" ? "" : "`n") files
	Sort, txt , U ;Remove duplicates
	CopyToClipboard(txt, true, cut)
	return
}


  • Guests
  • Last active:
  • Joined: --
the script does not work any more in Win 7?

I'm new, so sorry if I make a mistake. My script is:

   FileToClipboard(PathToCopy,Method="copy")
      {
      Loop,Parse,PathToCopy,`n,`r
         {
         Loop,%A_LoopField%,1
            {
            temp_list .= A_LoopFileLongPath "`n"
            }
         }           
      PathToCopy := SubStr(temp_list,1,-1)

      hPath := DllCall("GlobalAlloc","uint",0x42,"uint",StrLen(PathToCopy)+22)
      pPath := DllCall("GlobalLock","uint",hPath)
      NumPut(20,pPath+0)
      pPath += 20
      Loop,Parse,PathToCopy,`n,`r
         {
         DllCall("lstrcpy","uint",pPath+0,"str",A_LoopField)
         pPath += StrLen(A_LoopField)+1
         }
      DllCall("GlobalUnlock","uint",hPath)
      DllCall("OpenClipboard","uint",0)
      DllCall("EmptyClipboard")
      DllCall("SetClipboardData","uint",0xF,"uint",hPath)

      mem := DllCall("GlobalAlloc","UInt",2,"UInt",4)
      str := DllCall("GlobalLock","UInt",mem)
      if Method=copy
         DllCall("RtlFillMemory","UInt",str,"UInt",1,"UChar",0x05)
      else if Method=cut
         DllCall("RtlFillMemory","UInt",str,"UInt",1,"UChar",0x02)
      else
         {
         DllCall("CloseClipboard")
         return
         }
      DllCall("RtlZeroMemory","UInt",str + 1,"UInt",1)
      DllCall("RtlZeroMemory","UInt",str + 2,"UInt",1)
      DllCall("RtlZeroMemory","UInt",str + 3,"UInt",1)
      DllCall("GlobalUnlock","UInt",mem)

      cfFormat := DllCall("RegisterClipboardFormat","Str","Preferred DropEffect")
      DllCall("SetClipboardData","UInt",cfFormat,"UInt",mem)
      DllCall("CloseClipboard")
      return
      }
^m::FileToClipboard("D:\aadfadf.txt")


A_Samurai
  • Members
  • 30 posts
  • Last active: Jan 22 2012 01:53 PM
  • Joined: 29 Aug 2011
I wrote a similar function. <!-- m -->http://www.autohotke...pic.php?t=78261<!-- m -->
#persistent
InvokeVerb("D:\aadfadf.txt", "Copy")

English teachers are welcome.

maraskan_user
  • Members
  • 52 posts
  • Last active: Dec 08 2014 11:18 PM
  • Joined: 20 Jun 2008

the script does not work any more in Win 7?


That script was from before unicode and x64 support was added to Autohotkey, and depending on which version of Autohotkey and Windows 7 you're using, might not work anymore. fragman posted a version that should support those features just before your post. Try his, or use this (which is basically most of his changes merged into the old script):

FileToClipboard(PathToCopy,Method="copy")
   {
   FileCount:=0
   PathLength:=0

   ; Count files and total string length
   Loop,Parse,PathToCopy,`n,`r
      {
      FileCount++
      PathLength+=StrLen(A_LoopField)
      }

   pid:=DllCall("GetCurrentProcessId","uint")
   hwnd:=WinExist("ahk_pid " . pid)
   ; 0x42 = GMEM_MOVEABLE(0x2) | GMEM_ZEROINIT(0x40)
   hPath := DllCall("GlobalAlloc","uint",0x42,"uint",20 + (PathLength + FileCount + 1) * 2,"UPtr")
   pPath := DllCall("GlobalLock","UPtr",hPath)
   NumPut(20,pPath+0),pPath += 16 ; DROPFILES.pFiles = offset of file list
   NumPut(1,pPath+0),pPath += 4 ; fWide = 0 -->ANSI,fWide = 1 -->Unicode
   Offset:=0
   Loop,Parse,PathToCopy,`n,`r ; Rows are delimited by linefeeds (`r`n).
      offset += StrPut(A_LoopField,pPath+offset,StrLen(A_LoopField)+1,"UTF-16") * 2

   DllCall("GlobalUnlock","UPtr",hPath)
   DllCall("OpenClipboard","UPtr",hwnd)
   DllCall("EmptyClipboard")
   DllCall("SetClipboardData","uint",0xF,"UPtr",hPath) ; 0xF = CF_HDROP

   ; Write Preferred DropEffect structure to clipboard to switch between copy/cut operations
   ; 0x42 = GMEM_MOVEABLE(0x2) | GMEM_ZEROINIT(0x40)
   mem := DllCall("GlobalAlloc","uint",0x42,"uint",4,"UPtr")
   str := DllCall("GlobalLock","UPtr",mem)

   if (Method="copy")
      DllCall("RtlFillMemory","UPtr",str,"uint",1,"UChar",0x05)
   else if (Method="cut")
      DllCall("RtlFillMemory","UPtr",str,"uint",1,"UChar",0x02)
   else
      {
      DllCall("CloseClipboard")
      return
      }

   DllCall("GlobalUnlock","UPtr",mem)

   cfFormat := DllCall("RegisterClipboardFormat","Str","Preferred DropEffect")
   DllCall("SetClipboardData","uint",cfFormat,"UPtr",mem)
   DllCall("CloseClipboard")
   return
   }

#F9::FileToClipboard("D:\aadfadf.txt")




nimda
  • Members
  • 4368 posts
  • Last active: Aug 09 2015 02:36 AM
  • Joined: 26 Dec 2010
Just for reference, this can be done sans-dllcall with the new InvokeVerb() in the Scripts & Functions forum

randomguy
  • Members
  • 94 posts
  • Last active: Oct 20 2017 11:11 PM
  • Joined: 30 Oct 2011
you all are amazing. It works! I'd really like to try out the other Invoke context menu function as well, especially to clean the recycle bin.

Thanks!

(I'm the guest user above)

randomguy
  • Members
  • 94 posts
  • Last active: Oct 20 2017 11:11 PM
  • Joined: 30 Oct 2011
oh silly me. I just learnt also about the FileRecycleEmpty command :D