In my application I have a pictureBox
that shows an image. When user right clicks on the pictureBox
and selects Copy
from the context menu, I want to copy the image into the clipboard so the user can paste it in folders and anywhere else. How can I do that?
EDIT: I use this code but by this user only can paste image into word.
var img = Image.FromFile(pnlContent_Picture_PictureBox.ImageLocation);
Clipboard.SetImage(img);
Clipboard.SetImage
copies the image content (binary data) to the clipboard not the file path. To paste a file in Windows Explorer you need to have file paths collection in the clipboard not their content.
You can simply add the path of that image file to a StringCollection
and then call the SetFileDropList
method of Clipboard
to achieve what you want.
System.Collections.Specialized.StringCollection FileCollection = new System.Collections.Specialized.StringCollection();
FileCollection.Add(pnlContent_Picture_PictureBox.ImageLocation);
Clipboard.SetFileDropList(FileCollection);
Now user can past the file anywhere e.g. Windows Explorer.
More info on Clipboard.SetFileDropList Method
http://msdn.microsoft.com/en-us/library/system.windows.forms.clipboard.setfiledroplist.aspx
This is the solution when the picture box does not display a file image, but it is rendered upon with 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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With