5

次の 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);
}

このスニペットはhereから取得しました。コントロールは if 条件に入ります。Clipboard.GetImage()null を返します。誰かがここで何がうまくいかないのか提案してもらえますか?

次のスニペットも試しました

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();

これもうまくいきません。

4

2 に答える 2

6

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);

これで、メタファイルを読み取ることができます:

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();
}

私の最初の要件には、そのメタファイルの処理がさらに含まれているため、次を作成します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
    }
}
于 2015-04-28T15:46:58.993 に答える
1

次のコードが機能します。必要に応じて、保存する画像の形式を変更できます。

 if (Clipboard.ContainsImage())
 {
     Image image = Clipboard.GetImage();
     image.Save(@"c:\temp\image.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
 }
于 2013-10-15T05:55:18.737 に答える