GetClipboardFiles() - Get list of copied files as filepaths

Got an idea for enhancing PureBasic? New command(s) you'd like to see?
Axeman
User
User
Posts: 91
Joined: Mon Nov 03, 2003 5:34 am

GetClipboardFiles() - Get list of copied files as filepaths

Post by Axeman »

A common problem app coders have is getting the filepaths of files that the app user has copied to the clipboard for the app to process in some way. I think a 'GetClipboardFiles()' function would be a useful addition to the clipboard library.

Here's a Windows API function I use in some jigsaw puzzle generator software I'm working on which does something similar to what a 'GetClipboardFiles()' function would do. Basically it looks for the #CF_HDROP clipboard format (which seems to be available whenever a list of files is copied to the clipboard), and then copies the filepaths to the TempStringList() linked list.

Code: Select all

Procedure PasteSourceImagesFromClipboard()
; Grab a list of copied files off the clipboard if any exist, and then add them to the current project if they are compatible.
; Note that the #MAX_PATH constant is a predefined constant in PB. It has a value of 260 (the max number of chars in a filepath, including the terminating null character). 

If G_current_project_exists ; Check that a project actually exists.
	ClearList( TempStringList() ) ; Make sure that the list is clear to be on the safe side.
	
	If OpenClipboard_( G_main_window_system_id )
	
		; Check if the #CF_HDROP format for dropped files is available.
		format = 0		
		Repeat
			format = EnumClipboardFormats_( format )
			If format = #CF_HDROP : Break : EndIf
		Until format = 0	
			
		; If the #CF_HDROP format for dropped files is available.
		If format = #CF_HDROP ; #CF_HDROP = 15 - https://msdn.microsoft.com/en-us/library/windows/desktop/ff729168(v=vs.85).aspx
		
			; GetClipboardData -https://msdn.microsoft.com/en-us/library/windows/desktop/ms649039(v=vs.85).aspx
			; Note that the handle returned is owned by the clipboard and should not be closed or locked by my app.
			handle = GetClipboardData_( #CF_HDROP )
			If handle <> #Null
				num_files = DragQueryFile_( handle, $FFFFFFFF, 0, 0 )
				If num_files
					max_index = num_files - 1
					buffer.s = Space( #MAX_PATH )
					For i = 0 To max_index
						num_chars = DragQueryFile_( handle, i, @buffer.s, #MAX_PATH ) ; When the function copies a file name to the buffer, the return value is a count of the characters copied, not including the terminating null character.
						If num_chars
							filepath.s = Trim( Left( buffer.s, num_chars ) )
							If filepath.s
								AddElement( TempStringList() )
								TempStringList() = filepath.s
							EndIf
						EndIf
					Next
				EndIf
			EndIf
		EndIf
		
		CloseClipboard_()
	EndIf
	
	AddSourceImagesToProject() ; Add the new source images to the current project.
	ClearList( TempStringList() ) ; Clear the list after use.
EndIf
EndProcedure