1

I am trying to store items in the clipboard as a byte array.

I have the following function which does this for me.

public static byte[] GetClipboardDataBytes(uint format)
{
    var dataPointer = GetClipboardData(format);

    var length = GlobalSize(dataPointer);
    if(length == UIntPtr.Zero)
    {
        throw new Win32Exception(Marshal.GetLastWin32Error());
    }

    var lockedMemory = GlobalLock(dataPointer);
    if(lockedMemory == IntPtr.Zero)
    {
        throw new Win32Exception(Marshal.GetLastWin32Error());
    }

    var buffer = new byte[(int)length];

    Marshal.Copy(lockedMemory, buffer, 0, (int)length);

    GlobalUnlock(dataPointer);

    return buffer;
}

This works fine for file formats (CF_HDROP) and for text formats (CF_TEXT etc), but not for CF_BITMAP. In that case, length is 0, producing the following exception description:

Win32Exception (0x80004005): The handle is invalid

Am I doing something wrong?

Is it really not possible to make a generic function which can always fetch the standard formats that are available in the clipboard and store them?

Mathias Lykkegaard Lorenzen
  • 15,031
  • 23
  • 100
  • 187

1 Answers1

1

What you are attempting is impossible. Clipboard data is not compelled to stream to byte arrays.

A bitmap is a good example. The data isn't a byte array. You can extract an HBITMAP but that's not a byte array. You can stream a bitmap handle to its .bmp file representation, but that requires bespoke code that understands that specific format.

For general formats that your application can have no knowledge of, you have no chance of persisting to a byte array.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
  • Interesting. Let's then play around with the idea that I extract whatever is in the clipboard, and then 10 minutes later *inject* that **exact** same data again. Would that work, even if it was a `HBITMAP`? I am building a clipboard manager, that's why I ask. – Mathias Lykkegaard Lorenzen Aug 31 '15 at 16:46
  • The answer is correct, but actually, bitmap isn't a very good example: most applications put it on the clipboard as Device Independent Bitmap byte stream as well as in the standard Bitmap type, and often as PNG byte stream too. Though of course, these have their own data type identifiers. For the actual standard "bitmap" format this is 100% correct. – Nyerguds Oct 05 '17 at 07:13
  • The question was explicitly about CF_BITMAP – David Heffernan Oct 05 '17 at 11:04
  • David could you reply to my first comment? – Mathias Lykkegaard Lorenzen Apr 13 '18 at 12:13
  • Simple answer to the question in that comment. No. – David Heffernan Apr 13 '18 at 12:25