Skip to content

Commit

Permalink
Merge pull request #2701 from cwensley/curtis/wpf-fix-screen-getimage…
Browse files Browse the repository at this point in the history
…-leak

Wpf: Fix memory leak with Screen.GetImage()
  • Loading branch information
cwensley authored Nov 15, 2024
2 parents 3dcde01 + f4e8c3b commit 7fe8980
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 10 deletions.
3 changes: 3 additions & 0 deletions src/Eto.WinForms/Win32.gdi.cs
Original file line number Diff line number Diff line change
Expand Up @@ -86,5 +86,8 @@ public static List<FontRange> GetUnicodeRangesForFont(this sd.Font font)
g.Dispose();
return fontRanges;
}

[DllImport("gdi32.dll")]
public static extern bool DeleteObject(IntPtr hObject);
}
}
3 changes: 3 additions & 0 deletions src/Eto.Wpf/Eto.Wpf.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,9 @@ You do not need to use any of the classes of this assembly (unless customizing t
<Compile Include="..\Eto.WinForms\Win32.dpi.cs">
<Link>Win32.dpi.cs</Link>
</Compile>
<Compile Include="..\Eto.WinForms\Win32.gdi.cs">
<Link>Win32.gdi.cs</Link>
</Compile>
<Compile Include="..\Eto.WinForms\WinConversions.shared.cs">
<Link>WinConversions.shared.cs</Link>
</Compile>
Expand Down
28 changes: 18 additions & 10 deletions src/Eto.Wpf/Forms/ScreenHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -56,16 +56,24 @@ public Image GetImage(RectangleF rect)
using (var bmpGraphics = sd.Graphics.FromImage(screenBmp))
{
bmpGraphics.CopyFromScreen(realRect.X, realRect.Y, 0, 0, realRect.Size.ToSD());
var bitmapSource = sw.Interop.Imaging.CreateBitmapSourceFromHBitmap(
screenBmp.GetHbitmap(),
IntPtr.Zero,
sw.Int32Rect.Empty,
sw.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());

if (oldDpiAwareness != Win32.DPI_AWARENESS_CONTEXT.NONE)
Win32.SetThreadDpiAwarenessContextSafe(oldDpiAwareness);

return new Bitmap(new BitmapHandler(bitmapSource));
var hbmp = screenBmp.GetHbitmap();
try
{
var bitmapSource = sw.Interop.Imaging.CreateBitmapSourceFromHBitmap(
hbmp,
IntPtr.Zero,
sw.Int32Rect.Empty,
sw.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());

if (oldDpiAwareness != Win32.DPI_AWARENESS_CONTEXT.NONE)
Win32.SetThreadDpiAwarenessContextSafe(oldDpiAwareness);

return new Bitmap(new BitmapHandler(bitmapSource));
}
finally
{
Win32.DeleteObject(hbmp);
}
}
}
}
Expand Down

0 comments on commit 7fe8980

Please sign in to comment.