I am trying to fetch a Device Independent Bitmap from the clipboard. I am well-aware that this can be done through the Clipboard.GetData function inbuilt in the .NET Framework, but since it is very buggy (as documented many places on the web), I want to use the APIs only.
I have written the following code which works.
//i can correctly cast this to a MemoryStream
MemoryStream ms = Clipboard.GetData("DeviceIndependentBitmap") as MemoryStream;
But I want to use it with the APIs, which just return a pointer (an IntPtr) that point to the stream somehow. I took a look at the UnmanagedMemoryStream but fail to understand how to correctly convert an IntPtr
into that.
Here's my API code (using the GetClipboardData API where the CF_DIB
format is set as its argument).
IntPtr p = GetClipboardData(8);
//what do I do from here to get a MemoryStream from this pointer?
I'm a bit confused. I already researched it myself, but couldn't come up with something useful.
As you said you can use UnmanagedMemoryStream(byte* pointer, long length)
and to use it you should have a pointer and the length of the bytes. So you can use IntPtr.ToPointer()
method to get the pointer, but you should know the length of the memory content.
UnmanagedMemoryStream unmanagedmemstream = UnmanagedMemoryStream(p.ToPointer(), 100);
There is another method to retrieve an array of bytes, but also here you should know the length of the memory bytes that you want and it is Marshal.Copy(IntPtr source, byte[] destination, int startIndex,int length)
:
byte[] buffer = new byte[100];
Marshal.Copy(p , buffer, 0, buffer.Length);