c# - WPF Image: .Source = Clipboard.GetImage() is not displayed -


this simple program not work, image not appear in window.

namespace clipboardtest {     public partial class mainwindow : window     {         public mainwindow()         {             initializecomponent();         }         private void copybutton_click(object sender, routedeventargs e)         {             if (clipboard.containsimage())             {                 imageuielement.source = clipboard.getimage();                 console.writeline("clipboard copied uielement");             }             else             {                 console.writeline("no image in clipboard");             }         }     }  } 

output "clipboard copied uielement", image not appear in window.

xaml:

 <window x:class="clipboardtest.mainwindow"          xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"          xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"          title="mainwindow" height="350" width="525">      <grid>          <button x:name="copybutton" content="copy" horizontalalignment="left" margin="10,10,0,0" verticalalignment="top" width="75" click="copybutton_click"/>          <image x:name="imageuielement" margin="90,10,10,10"/>      </grid>  </window> 

is there anybody, understands, wrong?

use clipboard.getdataobject bitmap , convert bitmapsource. also, aware bitmap.gethbitmap() leaks memory unless call deleteobject on it.

so, correct solution dispose intptr after use. declare method @ class level , use code:

// @ class level [system.runtime.interopservices.dllimport("gdi32.dll")] public static extern bool deleteobject(intptr hobject); 

if (clipboard.containsimage()) {     idataobject clipboarddata = clipboard.getdataobject();     if (clipboarddata != null)     {         if (clipboarddata.getdatapresent(system.windows.forms.dataformats.bitmap))         {             system.drawing.bitmap bitmap = (system.drawing.bitmap)clipboarddata.getdata(system.windows.forms.dataformats.bitmap);             intptr hbitmap = bitmap.gethbitmap();             try             {                 imageuielement.source = system.windows.interop.imaging.createbitmapsourcefromhbitmap(hbitmap, intptr.zero, int32rect.empty, bitmapsizeoptions.fromemptyoptions());                 console.writeline("clipboard copied uielement");             }                          {                 deleteobject(hbitmap)             }         }     } } 

source - msdn , memory leak in bitmap.


Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

jsf - How to ajax update an item in the footer of a PrimeFaces dataTable? -

jquery - Keeping Kendo Datepicker in min/max range -