Skip to content

Commit cc2d520

Browse files
committed
chore: ScreenCapture add memory release function
1 parent f6401e6 commit cc2d520

1 file changed

Lines changed: 28 additions & 17 deletions

File tree

src/WPFDevelopers.Shared/Controls/ScreenCut/ScreenCapture.cs

Lines changed: 28 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66

77
namespace WPFDevelopers.Controls
88
{
9-
public class ScreenCapture
9+
public sealed class ScreenCapture
1010
{
1111
/// <summary>
1212
/// 截图完成委托
@@ -40,6 +40,27 @@ public class ScreenCapture
4040
/// </summary>
4141
private ResourceDictionary _resources;
4242

43+
private bool _disposed;
44+
45+
private void Dispose()
46+
{
47+
if (_disposed) return;
48+
_disposed = true;
49+
foreach (var sc in ScreenCuts)
50+
{
51+
sc.CutCompleted -= ScreenCut_CutCompleted;
52+
sc.CutCanceled -= ScreenCut_CutCanceled;
53+
sc.CutFullPath -= ScreenCut_CutFullPath;
54+
sc.Closed -= ScreenCut_Closed;
55+
if (sc.IsVisible)
56+
sc.Close();
57+
}
58+
ScreenCuts.Clear();
59+
GC.Collect();
60+
GC.WaitForPendingFinalizers();
61+
GC.Collect();
62+
}
63+
4364
public ScreenCapture(bool copyToClipboard = true)
4465
{
4566
if(System.Windows.Application.Current == null)
@@ -64,12 +85,14 @@ private ScreenCut CaptureScreen(int index)
6485

6586
private void ScreenCut_CutFullPath(string text)
6687
{
67-
if(SnapSaveFullPath != null) SnapSaveFullPath(text);
88+
if(SnapSaveFullPath != null) SnapSaveFullPath(text);
89+
Dispose();
6890
}
6991

7092
private void ScreenCut_CutCanceled()
7193
{
7294
if (SnapCanceled != null) SnapCanceled();
95+
Dispose();
7396
}
7497

7598
public void Capture()
@@ -87,29 +110,17 @@ private void ScreenCut_Closed(object sender, System.EventArgs e)
87110
if (ScreenCuts.Contains(screenCut))
88111
{
89112
ScreenCuts.Remove(screenCut);
90-
screenCut.CutCompleted -= ScreenCut_CutCompleted;
91-
screenCut.CutCanceled -= ScreenCut_CutCanceled;
92-
screenCut.CutFullPath -= ScreenCut_CutFullPath;
93-
screenCut.Closed -= ScreenCut_Closed;
94-
}
95-
CloseCutters();
96-
ScreenCut.ClearCaptureScreenID();
97-
}
98-
private void CloseCutters()
99-
{
100-
if (ScreenCuts.Count == 0) return;
101-
while (ScreenCuts.Count > 0)
102-
{
103-
ScreenCuts[0].Close();
104113
}
105-
ScreenCuts.Clear();
114+
Dispose();
106115
}
116+
107117
private void ScreenCut_CutCompleted(CroppedBitmap bitmap)
108118
{
109119
if (SnapCompleted != null)
110120
SnapCompleted(bitmap);
111121
if (_copyToClipboard)
112122
System.Windows.Clipboard.SetImage(bitmap);
123+
Dispose();
113124
}
114125
}
115126
}

0 commit comments

Comments
 (0)