I want to display a Bitmap
in an Image
container with WPF.
private void updateImagePreview()
{
Bitmap bmp = new Bitmap(Screen.PrimaryScreen.WorkingArea.Width,
Screen.PrimaryScreen.WorkingArea.Height);
Graphics gr = Graphics.FromImage(bmp);
Image Image_Preview;
while (true)
{
gr.CopyFromScreen(0, 0, 0, 0, new System.Drawing.Size(bmp.Width, bmp.Height));
Image_Preview.Source = loadBitmap(bmp);
}
}
[DllImport("gdi32")]
static extern int DeleteObject(IntPtr o);
public BitmapSource loadBitmap(System.Drawing.Bitmap source)
{
IntPtr ip = source.GetHbitmap();
BitmapSource bs = null;
try
{
bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
ip, IntPtr.Zero, Int32Rect.Empty,
System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
}
finally
{
DeleteObject(ip);
}
return bs;
}
The problem is, that this creates a huge memory leak. The leak occurs on the CreateBitmapSourceFromHBitmap
call and fills memory while looping till the limit is exceeded. If I don't use that call, then the leak disappears. Any idea why it happens?