2013-05-14 54 views
5

在我的应用程序中,我有一个显示图像的pictureBox。当用户右键单击pictureBox并从上下文菜单中选择Copy时,我想将图像复制到剪贴板,以便用户可以将其粘贴到文件夹和其他任何地方。我怎样才能做到这一点?允许用户从图片框复制图像并将其保存到处

编辑:我使用此代码,但由此用户只能将图像粘贴到单词中。

var img = Image.FromFile(pnlContent_Picture_PictureBox.ImageLocation); 
Clipboard.SetImage(img); 
+0

你到目前为止试过了什么?添加一些代码,让我们看看你已经做了什么,并帮助你通过其余的 – Mehran 2013-05-14 15:04:26

+0

我使用此代码,但由此用户只能将图像粘贴到单词中。 'var img = Image.FromFile(pnlContent_Picture_PictureBox.ImageLocation); Clipboard.SetImage(img);' – 2013-05-14 15:05:46

+0

图片框是否包含来自文件的图像,内存中的图像还是使用“Paint()”事件渲染? – ja72 2013-05-14 16:01:24

回答

4

Clipboard.SetImage将图像内容(二进制数据)复制到剪贴板而不是文件路径。要在Windows资源管理器中粘贴文件,您需要在剪贴板中包含文件路径集合而不是其内容。

您可以简单地将该图像文件的路径添加到StringCollection,然后调用ClipboardSetFileDropList方法来实现您想要的。

System.Collections.Specialized.StringCollection FileCollection = new System.Collections.Specialized.StringCollection(); 
FileCollection.Add(pnlContent_Picture_PictureBox.ImageLocation); 
Clipboard.SetFileDropList(FileCollection); 

现在用户可以通过任何地方的文件例如Windows资源管理器。在Clipboard.SetFileDropList Methodhttp://msdn.microsoft.com/en-us/library/system.windows.forms.clipboard.setfiledroplist.aspx

+1

完全有效,但这种方法有什么问题:'Clipboard.SetImage(pictureBox1.Image);' – Mehran 2013-05-14 15:32:06

+1

'Clipboard.SetImage'将图像内容(二进制数据)复制到剪贴板而不是文件路径。通过窗口中的文件浏览您需要在剪贴板中包含文件路径而不是其内容。 – 2013-05-14 15:39:25

+0

哦,现在我明白了,感谢Arash – Mehran 2013-05-14 15:40:22

3

更多信息是当图片对话框不显示文件图像的解决方案,但它是在与GDI +渲染。

public partial class Form1 : Form 
{ 
    private void pictureBox1_Paint(object sender, PaintEventArgs e) 
    { 
     // call render function 
     RenderGraphics(e.Graphics, pictureBox1.ClientRectangle); 
    } 

    private void pictureBox1_Resize(object sender, EventArgs e) 
    { 
     // refresh drawing on resize 
     pictureBox1.Refresh(); 
    } 

    private void copyToClipboardToolStripMenuItem_Click(object sender, EventArgs e) 
    { 
     // create a memory image with the size taken from the picturebox dimensions 
     RectangleF client=new RectangleF(
      0, 0, pictureBox1.Width, pictureBox1.Height); 
     Image img=new Bitmap((int)client.Width, (int)client.Height); 
     // create a graphics target from image and draw on the image 
     Graphics g=Graphics.FromImage(img); 
     RenderGraphics(g, client); 
     // copy image to clipboard. 
     Clipboard.SetImage(img); 
    } 

    private void RenderGraphics(Graphics g, RectangleF client) 
    { 
     g.SmoothingMode=SmoothingMode.AntiAlias; 
     // draw code goes here 
    } 
} 
相关问题