Copy filepath to clipboard in Windows Explorer

Post your working scripts, libraries and tools
capeably
Posts: 31
Joined: 10 Jul 2014, 14:38

Copy filepath to clipboard in Windows Explorer

07 Dec 2015, 16:42

Just a very simple script for setting a hotkey to copy selected file's path to clipboard *in Windows Explorer only*.

Demonstrated here:
https://youtu.be/JsmgPTuiZ30

Code: Select all

#NoEnv  ; Recommended for performance and compatibility with future AutoHotkey releases.
; #Warn  ; Enable warnings to assist with detecting common errors.
SendMode Input  ; Recommended for new scripts due to its superior speed and reliability.
SetWorkingDir %A_ScriptDir%  ; Ensures a consistent starting directory.
#SingleInstance Force  

#IfWinActive ahk_class CabinetWClass ; If Windows Explorer window is active

#NumpadAdd::
SendInput, ^c
Sleep 100
Clipboard := Clipboard
Return

#IfWinActive
User avatar
Flipeador
Posts: 1112
Joined: 15 Nov 2014, 21:31
GitHub: Flipeador
Location: Argentina
Contact:

Re: Copy filepath to clipboard in Windows Explorer

07 Dec 2015, 19:15

if anyone find it helpful, this makes the reverse operation:

Code: Select all

;-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
;EXAMPLE (AUTOHOTKEY UNICODE!)
;Tested on: WIN_7 PRO 32-Bits
;-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Clipboard := "" ;empty clipboard

;set clipboard text
OpenClipboard()
r := SetClipboardText("hello")
CloseClipboard()
MsgBox % r

;get clipboard text
OpenClipboard()
Text := GetClipboardText()
CloseClipboard()
MsgBox % Text

;copy two files to clipboard (try paste it from explorer)
OpenClipboard()
r := SetClipboardText( [ComSpec, A_WinDir "\explorer.exe"],, "Copy")
CloseClipboard()
MsgBox % r

;get clipboard text (the copied files)
OpenClipboard()
Text := GetClipboardText()
CloseClipboard()
MsgBox % Text

;cut file to clipboard
OpenClipboard()
r := SetClipboardText("C:\My_File.txt",, "Cut")
CloseClipboard()
MsgBox % r

;empty clipboard & close
OpenClipboard()
EmptyClipboard()
CloseClipboard()
ExitApp

;-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
;FUNCTION
;-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
SetClipboardText(Text, Encoding := "CP0", Mode := "Str") {
	EmptyClipboard()
	if (Mode="Str") { ;Text
		hGlobal := GlobalAlloc(Bytes:=StrLen(Text) + 1), hLockGlob := GlobalLock(hGlobal)
		, StrPut(Text, hLockGlob+0, Bytes, Encoding), GlobalUnlock(hGlobal)
		return r := SetClipboardData(0x1, hGlobal), ErrorLevel := !r
	} else if (Mode="Copy") || (Cut:=(Mode="Cut")) { ;Copy | Cut
		Files := GetValidArrayFiles(Text,,, Length)
		, hGlobal := GlobalAlloc(20 + (Length + Files.MaxIndex() + 1) * 2, 0x42)
		, hLockGlob := GlobalLock(hGlobal), NumPut(20, hLockGlob+0, 0, "UInt") ;DROPFILES
		, NumPut(1, hLockGlob+0, 16, "UInt"), Offset := 0 ;0 = ANSI | 1 = UNICODE
		for k, v in Files
			Offset += StrPut(v, (hLockGlob+20)+Offset, StrLen(v)+1, "UTF-16") * 2
		GlobalUnlock(hGlobal), r := SetClipboardData(15, hGlobal)
		, hGlobal := GlobalAlloc(4, 0x42), hLockGlob := GlobalLock(hGlobal)
		, RtlFillMemory(hLockGlob, 1, Cut?0x02:0x05), GlobalUnlock(hGlobal) ;0x02 = cut | 0x05 = copy
		, f := SetClipboardData(RegisterClipboardFormat("Preferred DropEffect"), hGlobal)
		return f&&r, ErrorLevel := !f||!r
	} return false, ErrorLevel := true
}

GetClipboardText() {
	Format := GetClipboardFormat()
	if (Format.HasKey(15)) { ;Files (CF_HDROP)
		Text := GetClipboardData(15), hLockGlob := GlobalLock(Text)
		if !(Count:=DllCall("Shell32.dll\DragQueryFileW", "Ptr", hLockGlob, "UInt", 0xFFFFFFFF, "Ptr", 0, "UInt", 0))
			return "", ErrorLevel := true
		Loop, %Count%
			Size := DllCall("Shell32.dll\DragQueryFileW", "Ptr", hLockGlob, "UInt", A_Index-1, "Ptr", 0, "UInt", 0)
			, VarSetCapacity(Name, (Size+1) * 2, 0), DllCall("Shell32.dll\DragQueryFileW", "Ptr", hLockGlob
			, "UInt", A_Index-1, "Str", Name, "UInt", Size + 1), OutputVar .= Name=""?"":Name "`n"
		return RTrim(OutputVar, "`n"), GlobalUnLock(Text), ErrorLevel := OutputVar=""
	} else if (Unicode:=Format.HasKey(13)) || (Format.HasKey(1)) || (OEM:=Format.HasKey(7)) ;Text
		return StrGet(GetClipboardData(Unicode?13:OEM?7:1), Unicode?"UTF-16":"CP0"), ErrorLevel := false
	return "", ErrorLevel := 2
}

OpenClipboard(Wait := 1000, Delay := 50) {
	if !DllCall("User32.dll\OpenClipboard", "Ptr", A_ScriptHwnd, "Int") { 
		Loop 
			Sleep, %Delay%
		until ((r:=DllCall("User32.dll\OpenClipboard", "Ptr", A_ScriptHwnd, "Int"))||(A_Index=Round(Wait/Delay))) 
		return r
	} else return true
} 

CloseClipboard() {
	return DllCall("User32.dll\CloseClipboard", "Int")
}

EmptyClipboard() {
	return DllCall("User32.dll\EmptyClipboard", "Int")
}

SetClipboardData(Format, hMem) {
	return DllCall("User32.dll\SetClipboardData", "UInt", Format, "Ptr", hMem, "Ptr")
} ;https://msdn.microsoft.com/en-us/library/windows/desktop/ms649051(v=vs.85).aspx

GetClipboardData(Format) {
	return DllCall("User32.dll\GetClipboardData", "UInt", Format, "Ptr")
} ;https://msdn.microsoft.com/en-us/library/windows/desktop/ms649039(v=vs.85).aspx

GetClipboardFormat() {
	Format := {}
	Loop, Parse, % "2|8|17|5|0x0082|0x008E|0x0083|0x0081|14|0x0300|0x03FF|15|16|3|7|0x0080|9|10|0x0200|0x02FF|11|41|6|13|12", |
		if DllCall("User32.dll\IsClipboardFormatAvailable", "UInt", A_LoopField, "Int")
			Format[A_LoopField] := A_LoopField
	return Format
}

RegisterClipboardFormat(Format) {
	return DllCall("User32.dll\RegisterClipboardFormatW", "Ptr", &Format, "UInt")
}

GetValidArrayFiles(Files, Exist := true, Path := "", ByRef Length := "", RemoveDuplicates := true) {
	Items := [], Files := IsObject(Files)?GVAF_GetFiles(Files):StrSplit(Files, "`n", "`r"), Length := 0
	for k, v in Files
	{	if ((Exist && IsFile(Path v)) || !(Exist)) && !((v:=GetFullPathName(GetLongPathName(Path v)))="") && (Ok:=true) {
			if (RemoveDuplicates)
				for k2, v2 in Items 
					if (v=v2) && !(Ok:=false)
						break
			if (Ok) 
				Items.Push(v), Length += StrLen(v) 
	}} return Items.MaxIndex()?Items:0, ErrorLevel := Items.MaxIndex()?0:1
} GVAF_GetFiles(Array) {
	Items := []
	for k, v in Array {
		for k2, v2 in StrSplit(v, "`n", "`r")
			Items.Push(v2)
	} return Items
}

IsFile(Filename) {
	return (!InStr(i:=FileExist(Filename),"D")&&i)
}

GetFullPathName(Filename) {
	Size := DllCall("Kernel32.dll\GetFullPathNameW", "Str", Filename, "UInt", 0, "Ptr", 0, "PtrP", 0), VarSetCapacity(OutputVar, Size * 2, 0) 
	, r := DllCall("Kernel32.dll\GetFullPathNameW", "Str", Filename, "UInt", Size, "Str", OutputVar, "PtrP", 0)
	return r?RTrim(OutputVar, "\"):Filename, ErrorLevel := !r
}

GetLongPathName(Filename) {
	Size := DllCall("Kernel32.dll\GetLongPathNameW", "Str", "\\?\" Filename, "Ptr", 0, "UInt", 0), VarSetCapacity(OutputVar, Size * 2, 0)
	, r := DllCall("Kernel32.dll\GetLongPathNameW", "Str", "\\?\" Filename, "Str", OutputVar, "UInt", Size)
	return r?LTrim(OutputVar, "\\?\"):Filename, ErrorLevel := !r
}

GlobalLock(hMem) {
	return DllCall("Kernel32.dll\GlobalLock", "Ptr", hMem, "Ptr")
} GlobalAlloc(Bytes, Flags := 0x0002) {
	return DllCall("Kernel32.dll\GlobalAlloc", "UInt", Flags, "UInt", Bytes, "Ptr")
} GlobalUnlock(hMem) {
	return DllCall("Kernel32.dll\GlobalUnlock", "Ptr", hMem, "UInt")
}

RtlFillMemory(ByRef Destination, Bytes, Fill) {
	DllCall("ntdll.dll\RtlFillMemory", "Ptr", Destination, "UInt", Bytes, "UChar", Fill) 
} ;https://msdn.microsoft.com/en-us/library/windows/hardware/ff561870(v=vs.85).aspx
capeably
Posts: 31
Joined: 10 Jul 2014, 14:38

Re: Copy filepath to clipboard in Windows Explorer

07 Dec 2015, 22:07

Thanks for sharing Flip!

I'm sorry, I don't understand what you mean by "reverse operation". Can you explain what your script does? I'm sure I can find a use for it! :)
User avatar
Flipeador
Posts: 1112
Joined: 15 Nov 2014, 21:31
GitHub: Flipeador
Location: Argentina
Contact:

Re: Copy filepath to clipboard in Windows Explorer

07 Dec 2015, 22:19

This copies the selected file path to clipboard as text:

Code: Select all

SendInput, ^c
Sleep 100
Clipboard := Clipboard
but my script restores to paste (use) with Windows Explorer (see example).
nico14

Re: Copy filepath to clipboard in Windows Explorer

17 Feb 2017, 09:12

Hi, thanks for the script, It works almost perfectly... Almost because it does the job on files on my computer (eg on C:\ drive), however, when I try to apply the command on some file on network drive, script does not work (copyboard keeps previous value, no operation applied...)

any idea why ?
thanks !
User avatar
davebrny
Posts: 83
Joined: 05 Dec 2016, 06:26

Re: Copy filepath to clipboard in Windows Explorer

17 Feb 2017, 10:50

nico14 wrote:Hi, thanks for the script, It works almost perfectly... Almost because it does the job on files on my computer (eg on C:\ drive), however, when I try to apply the command on some file on network drive, script does not work (copyboard keeps previous value, no operation applied...)

any idea why ?
thanks !
maybe try using "clipWait, 1" instead of "sleep 100" since it might take a bit longer to access the network compared to a local file
stealzy
Posts: 82
Joined: 01 Nov 2015, 13:43

Re: Copy filepath to clipboard in Windows Explorer

17 Feb 2017, 11:09

Code: Select all

Hotkey IfWinActive, ahk_class CabinetWClass
Hotkey +^vk43, Explorer_CopySelPath

Explorer_CopySelPath() {
	if Path := _GetSelection()
		Clipboard := Path
}

_GetSelection(hwnd="") {
	hwnd := hwnd? hwnd:WinExist("A")
	WinGetClass class, ahk_id %hwnd%
	if (class ~= "Progman|WorkerW") {
		 ControlGet, files, List, Selected Col1, SysListView321, ahk_class %class%
		 Loop, Parse, files, `n, `r
				ToReturn .= A_Desktop "\" A_LoopField "`n"
	}
	else if (class ~= "(Cabinet|Explore)WClass") {
		 for window in ComObjCreate("Shell.Application").Windows
				if (window.hwnd==hwnd)
					 sel := window.Document.SelectedItems
		 for item in sel
				ToReturn .= item.path "`n"
	}
	if !ToReturn
		ToReturn := ExplorerPath(hwnd)
	return Trim(ToReturn,"`n")
}
ExplorerPath(_hwnd) {
	for Item in ComObjCreate("Shell.Application").Windows
		if (Item.hwnd = _hwnd)
			return, LTrim(Item.LocationURL, "file:///")
}
GS SAHU
Posts: 37
Joined: 29 Sep 2014, 12:18

Re: Copy filepath to clipboard in Windows Explorer

06 Mar 2017, 05:32

1. Create a file CopyPath.bat
2. write this line
echo %1 | %windir%\system32\clip.exe
3. save file
4. open run window and type
shell:sendto
and enter
copy file copyPath.bat to here.

when you want to CopyPath of any file. right click on it and goto send to >CopyPath.bat menu

selected file path will be copied to clipboard.
T-Rock
Posts: 22
Joined: 01 Feb 2015, 09:11

Re: Copy filepath to clipboard in Windows Explorer

06 Mar 2017, 06:11

This is already available in Windows native.
If you select a file or folder in Windows Explorer and press the "Shift"-key while opening the context menu through right-mouse-click, you can enter the menu item "Copy as path".
What I don't like is that the resulting string in the clipboard always is surrounded by quotation marks.
As far as I know this is available in Windows 7 and higher.
GS SAHU
Posts: 37
Joined: 29 Sep 2014, 12:18

Re: Copy filepath to clipboard in Windows Explorer

06 Mar 2017, 06:26

thanks
i did not see that.
User avatar
boiler
Posts: 2409
Joined: 21 Dec 2014, 02:44

Re: Copy filepath to clipboard in Windows Explorer

06 Mar 2017, 08:10

The method T-Rock mentioned also works if you select multiple files. I've used that to get a list of all files in a directory. And if I don't want the path, I can use an editor's find/replace all, then I have just the file names. (And do the same to get rid of the quotation marks.)
RiseUp
Posts: 27
Joined: 01 Oct 2013, 21:27

Re: Copy filepath to clipboard in Windows Explorer

12 Nov 2017, 22:06

capeably wrote:Just a very simple script for setting a hotkey to copy selected file's path to clipboard *in Windows Explorer only*.

Demonstrated here:
https://youtu.be/JsmgPTuiZ30

Code: Select all

#NoEnv  ; Recommended for performance and compatibility with future AutoHotkey releases.
; #Warn  ; Enable warnings to assist with detecting common errors.
SendMode Input  ; Recommended for new scripts due to its superior speed and reliability.
SetWorkingDir %A_ScriptDir%  ; Ensures a consistent starting directory.
#SingleInstance Force  

#IfWinActive ahk_class CabinetWClass ; If Windows Explorer window is active

#NumpadAdd::
SendInput, ^c
Sleep 100
Clipboard := Clipboard
Return

#IfWinActive
Thanks for sharing, capeably! It works great for me. But I've got to ask...what exactly is the script doing? It seems that the code is copying the file to the clipboard, and then setting the clipboard's contents to the clipboard. Why would that change the actual contents of the clipboard instead of keeping it the same?
User avatar
davebrny
Posts: 83
Joined: 05 Dec 2016, 06:26

Re: Copy filepath to clipboard in Windows Explorer

13 Nov 2017, 05:21

RiseUp wrote:what exactly is the script doing? It seems that the code is copying the file to the clipboard, and then setting the clipboard's contents to the clipboard. Why would that change the actual contents of the clipboard instead of keeping it the same?
try this out:
- select a file and press ctrl + c
- paste the clipboard into the address bar, you should see the path wrapped in "quotes"
- paste the same thing into a text file, you will see that the clipboard is empty
- paste into the address bar again... its back!
User avatar
jeeswg
Posts: 6469
Joined: 19 Dec 2016, 01:58
Location: UK

Re: Copy filepath to clipboard in Windows Explorer

13 Nov 2017, 06:23

clipboard: remove individual clipboard formats + save to clp file - AutoHotkey Community
https://autohotkey.com/boards/viewtopic.php?f=6&t=39522

I talk about clipboard formats in the link above, you can have all sorts of clipboard formats on the clipboard at the same time, and they don't need to have anything to do with each other, you can have RTF for WordPad, HTML for Excel, text for Notepad, an image for Paint, a file list for Explorer, all sorts.

Clipboard and ClipboardAll
https://autohotkey.com/docs/misc/Clipboard.htm

- ClipSaved := ClipboardAll stores the entire contents of the clipboard (or almost does).
- var := Clipboard looks at all of the clipboard formats on the clipboard, and if there is an appropriate clipboard format, e.g. text, or a list of files, it retrieves the text from it.
- Clipboard := var empties the clipboard, it deletes all of the clipboard formats on the clipboard, it then places raw text onto the clipboard.
- So, the effect of Clipboard := Clipboard, after a file copy operation, is to: (temporarily) store the list of files that were copied, clear the contents of the clipboard, set the contents of the clipboard to the list of files as raw text. You will no longer be able to paste the files anywhere.
- If you copy html from Internet Explorer for example, one of the clipboard formats put onto the clipboard is raw text. If you then do Clipboard := Clipboard, AutoHotkey sets the clipboard to store only the raw text, and discards all of the other clipboard formats, thus Clipboard := Clipboard gives you a way to strip formatting from what you copied from Internet Explorer. But it doesn't literally strip formatting, it finds a version of the text without formatting that Internet Explorer had provided.

Some links for clipboard manipulation are available here:
GUI COMMANDS: COMPLETE RETHINK - Page 2 - AutoHotkey Community
https://autohotkey.com/boards/viewtopic ... 42#p144342
GUI COMMANDS: COMPLETE RETHINK - Page 2 - AutoHotkey Community
https://autohotkey.com/boards/viewtopic ... 34#p170834
homepage | tutorials | wish list | fun threads | donate
WARNING: copy your posts/messages before hitting Submit as you may lose them due to CAPTCHA
RiseUp
Posts: 27
Joined: 01 Oct 2013, 21:27

Re: Copy filepath to clipboard in Windows Explorer

13 Nov 2017, 10:47

@davebrny, Ha! The magic of Windows! :crazy:

@jeeswg, Thanks for the detailed explanation! I'll check out those links in time, but what you've written makes perfect sense to me now.

Gotta love this community. :D
robertoleonardo

Re: Copy filepath to clipboard in Windows Explorer

24 Jun 2018, 11:19

I spent a bunch of time trying to figure this out on my own to no avail, but is there some way to call the windows native method that t-rock mentioned through AHK? Bottom line is: i like how it works (e.g., with quotes, and separated by lines, when i have multiple files when i manually do copy path in explorer or in the context menu, and i have hotkeys working that open the context menu and select that option - but it's always a bit slow and it would be awesome to just call that feature directly.

alternatively, there's probably a way to add the quotes through AHK, but also struggled with that. i figured out how to copy path through clipboard with quotes only to copy back into the explorer address bar, but when i converted to plain text so that i could copy it into, for example, note pad - i lost the quotes. i figured out how to put quotes around the clipboard contents, but this only works when i copy a single path. for multiple paths, i tried to do a string replace to replace new lines with a " + new line + " - but no luck there either.

Return to “Scripts and Functions”

Who is online

Users browsing this forum: freespacing, Ovg, robodesign and 34 guests