#700 – Dragging an Image to Microsoft Word

You can use the drag and drop functionality in WPF to drag an Image control out of the application.  You can drop this image onto a Word document if you convert the image to an enhanced metafile format.

Here’s the code that initiates the drag operation.

        private void Image_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            Bitmap bitmap = ImageToBitmap(e.Source as System.Windows.Controls.Image);

            DataObject data = new DataObject(DataFormats.EnhancedMetafile, MakeMetafileStream(bitmap));

            DragDrop.DoDragDrop((DependencyObject)e.Source, data, DragDropEffects.Copy);
        }

This makes use of a utility function to convert the Image to a Bitmap:

        private Bitmap ImageToBitmap(System.Windows.Controls.Image image)
        {
            RenderTargetBitmap rtBmp = new RenderTargetBitmap((int)image.ActualWidth, (int)image.ActualHeight,
                96.0, 96.0, PixelFormats.Pbgra32);

            image.Measure(new System.Windows.Size((int)image.ActualWidth, (int)image.ActualHeight));
            image.Arrange(new Rect(new System.Windows.Size((int)image.ActualWidth, (int)image.ActualHeight)));

            rtBmp.Render(image);

            PngBitmapEncoder encoder = new PngBitmapEncoder();
            MemoryStream stream = new MemoryStream();
            encoder.Frames.Add(BitmapFrame.Create(rtBmp));

            // Save to memory stream and create Bitamp from stream
            encoder.Save(stream);

            return new System.Drawing.Bitmap(stream);
        }

This also requires a utility function that converts a Bitmap to a stream containing a Metafile, taken from Stack Overflow.

        // From http://stackoverflow.com/questions/5270763/convert-an-image-into-wmf-with-net
        private MemoryStream MakeMetafileStream(Bitmap image)
        {
            Graphics graphics = null;
            Metafile metafile = null;
            var stream = new MemoryStream();
            try
            {
                using (graphics = Graphics.FromImage(image))
                {
                    var hdc = graphics.GetHdc();
                    metafile = new Metafile(stream, hdc);
                    graphics.ReleaseHdc(hdc);
                }
                using (graphics = Graphics.FromImage(metafile))
                { graphics.DrawImage(image, 0, 0); }
            }
            finally
            {
                if (graphics != null)
                { graphics.Dispose(); }
                if (metafile != null)
                { metafile.Dispose(); }
            }
            return stream;
        }

Here’s the code in action:

Advertisement