Search code examples
c++windowswinapiclipboard

Save data from HANDLE to a file and load data from file to a HANDLE without data loss


Are there any ways (or functions) to save data from HANDLE to a file without data loss and load data from file to a HANDLE? Assuming that it's a HANDLE to a data obtained from GetClipboardData.

It would be great if there are answers for all possible data types in clipboard formats but I would look by piority for CF_LOCALE, CF_TEXT, CF_OEMTEXT and CF_UNICODETEXT.

I tried to convert from HANDLE to pointer but I don't know how to get the data properly (as the handle only point to the first data without further information)

I tried to obtain some useful handle information to know what is possibly inside, but I cannot retrieve it.

There are too few attempts to try as very few (or no one) asked about this question...


Solution

  • There is no pre-existing solution to handle this task for you. You will have to do everything manually.

    Use EnumClipboardFormats() to find which formats are currently available on the clipboard, and GetClipboardData() to access the data of each format.

    Or, use OleGetClipboard() to get an IDataObject wapping the clipboard's content, and then enumerate and access its data formats using its EnumFormatEtc() and GetData() methods.

    Then, you can manually write each format's data to your own file as needed, and then later read the data back from your file and put it back on the clipboard according to each format type using SetClipboardData() or OleSetClipboard().

    The data formats of the standard clipboard formats are documented on MSDN:

    Standard Clipboard Formats

    Shell Clipboard Formats

    For example, a HANDLE for a CF_LOCALE is an HGLOBAL handle to an allocated block of memory holding a LCID identifier, whereas a HANDLE for a CF_TEXT/CF_UNICODETEXT is an HGLOBAL handle to an allocated block of memory holding the actual ANSI/Unicode text characters.

    If you want to save/load data for non-standard clipboard formats, you won't be able to do that unless you have intimate knowledge of how their data is formatted in memory for the clipboard to hold.