我有一个 Silverlight 5 应用程序,它在浏览器中运行提升的信任度。这使我们能够做一些在silverlight 中通常不可能的事情,比如通过P/Invoke 对剪贴板进行更多访问。
我需要做的是将控件复制到剪贴板,以便将它们粘贴到 Word 或 Outlook 中。我可以通过 WriteableBitmap 将控件转换为图像,但是将数据复制到剪贴板是我遇到的问题。
调用代码:
WriteableBitmap bmp = new WriteableBitmap(elements[0], new ScaleTransform() { ScaleX = 1.0, ScaleY = 1.0 });
int[] p = bmp.Pixels;
int len = p.Length * 4;
byte[] result = new byte[len];
Buffer.BlockCopy(p, 0, result, 0, len);
CopyToClipboardViaPInvoke(result, ClipboardFormat.CF_BITMAP);
复制功能:
private void CopyToClipboardViaPInvoke(byte[] data, ClipboardFormat format)
{
IntPtr p = IntPtr.Zero;
if (Native.OpenClipboard(p))
{
GCHandle pinnedArray = GCHandle.Alloc(data, GCHandleType.Pinned);
IntPtr pointer = pinnedArray.AddrOfPinnedObject();
try
{
Native.EmptyClipboard();
IntPtr result = Native.SetClipboardData(format, pointer);
}
finally
{
Native.CloseClipboard();
pinnedArray.Free();
}
}
}
结果表明它是成功的,但是 paste 什么也没做。IsClipboardFormatAvailable
还指出该格式在剪贴板上可用。我还尝试了各种 ClipboardFormat 输入和其他将控件转换为图像的方法,但没有任何运气。
更新 1
感谢 user629926 的建议,我已经得到了我认为更接近一点的东西,但我仍然缺少一些东西。
Native.EmptyClipboard();
IntPtr bmp = IntPtr.Zero;
GCHandle pinnedArray = GCHandle.Alloc(bytes, GCHandleType.Pinned);
IntPtr bmpPointer = pinnedArray.AddrOfPinnedObject();
Native.StartupInput sin = new Native.StartupInput() { GdiplusVersion = 1 };
Native.StartupOutput sout = new Native.StartupOutput();
IntPtr gdip = IntPtr.Zero;
int startup = Native.GdiplusStartup(out gdip, ref sin, out sout);
int created = Native.GdipCreateBitmapFromScan0(width, height, width * 4, 0x0026200A, bmpPointer, out bmp);
IntPtr result = Native.SetClipboardData(format, bmp);
Native.DeleteObject(bmp);
Native.GdiplusShutdown(ref gdip);