我正在将 Excel 文档中的单元格复制到剪贴板,以便它们可以作为图像插入到其他地方。单元格可以很好地复制到剪贴板,因为我可以在代码运行后手动粘贴图像。但是我无法获取数据。这是我的代码:
tempWorkSheet.Range[tempWorkSheet.Cells[1, 1], tempWorkSheet.Cells[3, 3]].CopyPicture(Excel.XlPictureAppearance.xlScreen, Excel.XlCopyPictureFormat.xlPicture);
// returns true
var test = Clipboard.GetDataObject().GetDataPresent(DataFormats.EnhancedMetafile);
// returns true
var test2 = Clipboard.ContainsData(DataFormats.EnhancedMetafile);
// returns null
var test3 = Clipboard.GetData(DataFormats.EnhancedMetafile);
// returns null
var test4 = Clipboard.GetDataObject().GetData(DataFormats.EnhancedMetafile);
数据存储为EnhancedMetaFile
我可以看到其中的数据,但无法将其取出。我束手无策,试图弄清楚这一点。有人看到我缺少的东西吗?
I saw this http://social.msdn.microsoft.com/Forums/windows/en-US/ea562ff1-9558-425d-a30a-6a1809224edc/how-best-to-avoid-the-land-mines-planted-in-the-idataobject-returned-from-clipboardgetdataobject?forum=winforms问题已发布,但对我没有多大帮助。我希望有人可以。
我找到了解决方案。这Clipboard.GetData(DataFormats.EnhancedMetafile)
通话似乎中断了。但我设法使用 P/Invoke 让它工作。
这不是最漂亮的代码,但它有效,所以对于后代来说,它是最荣耀的:
[DllImport("user32.dll", SetLastError = true)]
static extern bool OpenClipboard(IntPtr hWndNewOwner);
[DllImport("user32.dll")]
static extern IntPtr GetClipboardData(uint uFormat);
[DllImport("user32.dll", SetLastError = true)]
static extern bool CloseClipboard();
[DllImport("user32.dll")]
static extern bool EmptyClipboard();
[DllImport("gdi32.dll")]
static extern IntPtr CopyEnhMetaFile(IntPtr hemfSrc, string lpszFile);
[DllImport("gdi32.dll")]
static extern bool DeleteEnhMetaFile(IntPtr hemf);
public Image GetMetaImageFromClipboard()
{
OpenClipboard(IntPtr.Zero);
IntPtr pointer = GetClipboardData(14);
string fileName = @"C:\Test\" + Guid.NewGuid().ToString() + ".emf";
IntPtr handle = CopyEnhMetaFile(pointer, fileName);
Image image;
using (Metafile metafile = new Metafile(fileName))
{
image = new Bitmap(metafile.Width, metafile.Height);
Graphics g = Graphics.FromImage(image);
EmptyClipboard();
CloseClipboard();
g.DrawImage(metafile, 0, 0, image.Width, image.Height);
}
DeleteEnhMetaFile(handle);
File.Delete(fileName);
return image;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)