Skip to content

Instantly share code, notes, and snippets.

@valuex
Created November 24, 2024 03:25
Show Gist options
  • Save valuex/5ba9ca34e0dcfeaa2180f6354c0de8dc to your computer and use it in GitHub Desktop.
Save valuex/5ba9ca34e0dcfeaa2180f6354c0de8dc to your computer and use it in GitHub Desktop.
Copy File To Clipboard
;https://www.autohotkey.com/boards/viewtopic.php?t=120483
FileToClipboard(PathToCopy) {
; Expand to full path:
Loop Files, PathToCopy
PathToCopy := A_LoopFileFullPath
; Allocate some movable memory to put on the clipboard.
; This will hold a DROPFILES struct (20), the string, and an (extra) null terminator (2)
; 0x42 = GMEM_MOVEABLE(0x2) | GMEM_ZEROINIT(0x40)
hPath := DllCall("GlobalAlloc", "UInt", 0x42, "UInt", 20 + (StrPut(PathToCopy) + 22), "UPtr")
; Lock the moveable memory, retrieving a pointer to it.
pPath := DllCall("GlobalLock", "Ptr", hPath, "UPtr")
NumPut("UInt", 20, pPath) ; DROPFILES.pFiles = offset of file list
NumPut("UInt", 1, pPath, 16) ; DROPFILES.fWide - 1 = Unicode
; Copy the string into moveable memory.
StrPut(PathToCopy, pPath + 20)
; Unlock the moveable memory.
DllCall("GlobalUnlock", "UPtr", hPath)
DllCall("OpenClipboard", "Ptr", 0)
; Empty the clipboard, otherwise SetClipboardData may fail.
DllCall("EmptyClipboard")
; Place the data on the clipboard. CF_HDROP=0xF
DllCall("SetClipboardData", "UInt", 0xF, "Ptr", hPath)
DllCall("CloseClipboard")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment