title: Receiving an image dragged from Web Page to WPF window
body: <p>I want my WPF application to be a drop target, and I want to be able to drag an image from any web page.</p>
  
  <p>When an image is dragged from a web page, apparently it is in the "DragImageBits" format, which can be deserialized to type <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/bb759778(v=vs.85).aspx">ShDragImage</a>. (See the bottom of the question for how I've defined it)</p>
  
  <p>How do I convert this to a WPF image?</p>
  
  <p>Here's my current attempt. (If anybody knows the correct way to do the desirialization, I'm all ears)</p>
  
  <pre><code>   private void UserControl_Drop(object sender, System.Windows.DragEventArgs e)
      {
  
              string[] formats = data.GetFormats();
  
              // DragImageBits
              if (formats.Contains("DragImageBits"))
              {
              MemoryStream imageStream = data.GetData("DragImageBits") as MemoryStream;
  
              // Now I'm deserializing this, the only way I know how
              imageStream.Seek(0, SeekOrigin.Begin);
              BinaryReader br = new BinaryReader(imageStream);
  
              ShDragImage shDragImage;
              shDragImage.sizeDragImage.cx = br.ReadInt32();
              shDragImage.sizeDragImage.cy = br.ReadInt32();
              shDragImage.ptOffset.x = br.ReadInt32();
              shDragImage.ptOffset.y = br.ReadInt32();
              shDragImage.hbmpDragImage = new IntPtr(br.ReadInt32());
              shDragImage.crColorKey = br.ReadInt32();
  
  
              var systemDrawingBitmap = System.Drawing.Bitmap.FromHbitmap(shDragImage.hbmpDragImage);
  </code></pre>
  
  <p>At this point I get an exception of type <code>System.Runtime.InteropServices.ExternalException</code>, with the message simply being <code>Generic GDI+ error</code>.</p>
  
  <p>Does anyone know what I should be doing?</p>
  
  <p><hr />
  And here are the supporting class definitions. I copied them from <a href="http://blogs.msdn.com/adamroot/pages/shell-style-drag-and-drop-in-net-wpf-and-winforms.aspx">this blog entry</a>.</p>
  
  <pre><code>[System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential)]
      public struct Win32Point
      {
          public int x;
          public int y;
      }
  
      [System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential)]
      public struct Win32Size
      {
          public int cx;
          public int cy;
      }
  
      [System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential)]
      public struct ShDragImage
      {
          public Win32Size sizeDragImage;
          public Win32Point ptOffset;
          public IntPtr hbmpDragImage;
          public int crColorKey;
      }
  </code></pre>