tra*_*zer 5 c# clipboard image
我正在使用以下 C# 代码从剪贴板复制图像。
if (Clipboard.ContainsData(System.Windows.DataFormats.EnhancedMetafile))
{
/* taken from http://social.msdn.microsoft.com/Forums/windowsdesktop/en-US/a5cebe0d-eee4-4a91-88e4-88eca9974a5c/excel-copypicture-and-asve-to-enhanced-metafile*/
var img = (System.Windows.Interop.InteropBitmap)Clipboard.GetImage();
var bit = Clipboard.GetImage();
var enc = new System.Windows.Media.Imaging.JpegBitmapEncoder();
var stream = new FileStream(fileName + ".bmp", FileMode.Create);
enc.Frames.Add(BitmapFrame.Create(bit));
enc.Save(stream);
}
Run Code Online (Sandbox Code Playgroud)
我从这里拿了这个片段。控件确实进入 if 条件。Clipboard.GetImage()返回空值。有人可以建议这里出了什么问题吗?
我也试过以下片段
Metafile metafile = Clipboard.GetData(System.Windows.DataFormats.EnhancedMetafile) as Metafile;
Control control = new Control();
Graphics grfx = control.CreateGraphics();
MemoryStream ms = new MemoryStream();
IntPtr ipHdc = grfx.GetHdc();
grfx.ReleaseHdc(ipHdc);
grfx.Dispose();
grfx = Graphics.FromImage(metafile);
grfx.Dispose();
Run Code Online (Sandbox Code Playgroud)
这也行不通。
您可以user32.dll通过 p/invoke 使用,如下所示:
public const uint CF_METAFILEPICT = 3;
public const uint CF_ENHMETAFILE = 14;
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
public static extern bool OpenClipboard(IntPtr hWndNewOwner);
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
public static extern bool CloseClipboard();
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
public static extern IntPtr GetClipboardData(uint format);
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
public static extern bool IsClipboardFormatAvailable(uint format);
Run Code Online (Sandbox Code Playgroud)
现在,您可以读取您的元文件:
Metafile emf = null;
if (OpenClipboard(IntPtr.Zero))
{
if (IsClipboardFormatAvailable(CF_ENHMETAFILE))
{
var ptr = GetClipboardData(CF_ENHMETAFILE);
if (!ptr.Equals(IntPtr.Zero))
emf = new Metafile(ptr, true);
}
// You must close ir, or it will be locked
CloseClipboard();
}
Run Code Online (Sandbox Code Playgroud)
我最初的要求涉及对该图元文件的更多处理,因此我创建了一个MemoryStream:
using (var graphics = Graphics.FromImage(new Bitmap(1,1,PixelFormat.Format32bppArgb)))
{
var hdc = graphics.GetHdc();
using (var original = new MemoryStream())
{
using (var dummy = Graphics.FromImage(new Metafile(original, hdc)))
{
dummy.DrawImage(emf, 0, 0, emf.Width, emf.Height);
dummy.Flush();
}
graphics.ReleaseHdc(hdc);
// do more stuff
}
}
Run Code Online (Sandbox Code Playgroud)
以下代码将起作用。如果需要,您可以更改保存的图像的格式。
if (Clipboard.ContainsImage())
{
Image image = Clipboard.GetImage();
image.Save(@"c:\temp\image.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
}
Run Code Online (Sandbox Code Playgroud)