我需要帮助将一个透明图像设置到剪贴板中。我一直收到“句柄无效”的错误提示。基本上,我需要一个“第二个眼睛”来检查以下代码。(完整的工作项目在ftp://missico.net/ImageVisualizer.zip)。这是一个图像Debug Visualizer类库,但我制作了包含的项目以便于测试运行。(请注意,窗口是一个工具箱窗口,显示在任务栏中设置为false。)我厌倦了在工具箱窗口上执行屏幕截图,使用图像编辑器打开屏幕截图,然后删除添加的背景,因为它是一个屏幕截图。所以我想我会快速地将透明图像放到剪贴板上。问题是...Clipboard.SetImage没有透明度支持。Google来拯救...还不够。这是我目前的进展情况。我从许多来源获取。请参见代码的主要参考。我的问题是使用CF_DIBV5时出现“无效句柄”。我需要使用BITMAPV5HEADER和CreateDIBitmap吗?非常感谢你们GDI/GDI+巫师的任何帮助。
public static void SetClipboardData(Bitmap bitmap, IntPtr hDC) {
const uint SRCCOPY = 0x00CC0020;
const int CF_DIBV5 = 17;
const int CF_BITMAP = 2;
//'reference
//'http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/816a35f6-9530-442b-9647-e856602cc0e2
IntPtr memDC = CreateCompatibleDC(hDC);
IntPtr memBM = CreateCompatibleBitmap(hDC, bitmap.Width, bitmap.Height);
SelectObject(memDC, memBM);
using (Graphics g = Graphics.FromImage(bitmap)) {
IntPtr hBitmapDC = g.GetHdc();
IntPtr hBitmap = bitmap.GetHbitmap();
SelectObject(hBitmapDC, hBitmap);
BitBlt(memDC, 0, 0, bitmap.Width, bitmap.Height, hBitmapDC, 0, 0, SRCCOPY);
if (!OpenClipboard(IntPtr.Zero)) {
throw new System.Runtime.InteropServices.ExternalException("Could not open Clipboard", new Win32Exception());
}
if (!EmptyClipboard()) {
throw new System.Runtime.InteropServices.ExternalException("Unable to empty Clipboard", new Win32Exception());
}
//IntPtr hClipboard = SetClipboardData(CF_BITMAP, memBM); //works but image is not transparent
//all my attempts result in SetClipboardData returning hClipboard = IntPtr.Zero
IntPtr hClipboard = SetClipboardData(CF_DIBV5, memBM);
//because
if (hClipboard == IntPtr.Zero) {
// InnerException: System.ComponentModel.Win32Exception
// Message="The handle is invalid"
// ErrorCode=-2147467259
// NativeErrorCode=6
// InnerException:
throw new System.Runtime.InteropServices.ExternalException("Could not put data on Clipboard", new Win32Exception());
}
if (!CloseClipboard()) {
throw new System.Runtime.InteropServices.ExternalException("Could not close Clipboard", new Win32Exception());
}
g.ReleaseHdc(hBitmapDC);
}
}
private void __copyMenuItem_Click(object sender, EventArgs e) {
using (Graphics g = __pictureBox.CreateGraphics()) {
IntPtr hDC = g.GetHdc();
MemoryStream ms = new MemoryStream();
__pictureBox.Image.Save(ms, ImageFormat.Png);
ms.Seek(0, SeekOrigin.Begin);
Image imag = Image.FromStream(ms);
// Derive BitMap object using Image instance, so that you can avoid the issue
//"a graphics object cannot be created from an image that has an indexed pixel format"
Bitmap img = new Bitmap(new Bitmap(imag));
SetClipboardData(img, hDC);
g.ReleaseHdc();
}
}