Search code examples
c#pngclipboarddataformat

Adding a png to clipboard


I have a simple question. What do I use as a DataFormat when saving a png to the clipboard.

An example that works for Bitmaps is:

DataObject data = new DataObject();
data.SetData(DataFormats.Bitmap, customObject.ToImage(ImageFormat.Bmp));
Clipboard.SetDataObject(data);

My problem:

DataObject data = new DataObject();
data.SetData(DataFormats.**???**, customObject.ToImage(ImageFormat.Png));
Clipboard.SetDataObject(data);

Solution

  • You can register any serializable type with the clipboard provider:

            Image image = Image.FromFile(@"D:\Documents\Projects\....\myimage.png");
            DataFormat format = DataFormats.GetDataFormat(typeof (Image).FullName);
    
            IDataObject dataObj = new DataObject();
            dataObj.SetData(format.Name, image);
    
            Clipboard.SetDataObject(dataObj);
    
            IDataObject clipboardObj = Clipboard.GetDataObject();
            Image clipboardImage = (Image)clipboardObj.GetData(format.Name);