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?
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.
User contributions licensed under CC BY-SA 3.0