Skip to content

Commit 7fe8980

Browse files
authored
Merge pull request #2701 from cwensley/curtis/wpf-fix-screen-getimage-leak
Wpf: Fix memory leak with Screen.GetImage()
2 parents 3dcde01 + f4e8c3b commit 7fe8980

File tree

3 files changed

+24
-10
lines changed

3 files changed

+24
-10
lines changed

src/Eto.WinForms/Win32.gdi.cs

+3
Original file line numberDiff line numberDiff line change
@@ -86,5 +86,8 @@ public static List<FontRange> GetUnicodeRangesForFont(this sd.Font font)
8686
g.Dispose();
8787
return fontRanges;
8888
}
89+
90+
[DllImport("gdi32.dll")]
91+
public static extern bool DeleteObject(IntPtr hObject);
8992
}
9093
}

src/Eto.Wpf/Eto.Wpf.csproj

+3
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,9 @@ You do not need to use any of the classes of this assembly (unless customizing t
101101
<Compile Include="..\Eto.WinForms\Win32.dpi.cs">
102102
<Link>Win32.dpi.cs</Link>
103103
</Compile>
104+
<Compile Include="..\Eto.WinForms\Win32.gdi.cs">
105+
<Link>Win32.gdi.cs</Link>
106+
</Compile>
104107
<Compile Include="..\Eto.WinForms\WinConversions.shared.cs">
105108
<Link>WinConversions.shared.cs</Link>
106109
</Compile>

src/Eto.Wpf/Forms/ScreenHandler.cs

+18-10
Original file line numberDiff line numberDiff line change
@@ -56,16 +56,24 @@ public Image GetImage(RectangleF rect)
5656
using (var bmpGraphics = sd.Graphics.FromImage(screenBmp))
5757
{
5858
bmpGraphics.CopyFromScreen(realRect.X, realRect.Y, 0, 0, realRect.Size.ToSD());
59-
var bitmapSource = sw.Interop.Imaging.CreateBitmapSourceFromHBitmap(
60-
screenBmp.GetHbitmap(),
61-
IntPtr.Zero,
62-
sw.Int32Rect.Empty,
63-
sw.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
64-
65-
if (oldDpiAwareness != Win32.DPI_AWARENESS_CONTEXT.NONE)
66-
Win32.SetThreadDpiAwarenessContextSafe(oldDpiAwareness);
67-
68-
return new Bitmap(new BitmapHandler(bitmapSource));
59+
var hbmp = screenBmp.GetHbitmap();
60+
try
61+
{
62+
var bitmapSource = sw.Interop.Imaging.CreateBitmapSourceFromHBitmap(
63+
hbmp,
64+
IntPtr.Zero,
65+
sw.Int32Rect.Empty,
66+
sw.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
67+
68+
if (oldDpiAwareness != Win32.DPI_AWARENESS_CONTEXT.NONE)
69+
Win32.SetThreadDpiAwarenessContextSafe(oldDpiAwareness);
70+
71+
return new Bitmap(new BitmapHandler(bitmapSource));
72+
}
73+
finally
74+
{
75+
Win32.DeleteObject(hbmp);
76+
}
6977
}
7078
}
7179
}

0 commit comments

Comments
 (0)