blob: 9933512c317c3af8ebaf5fd44cb2d2514f692bc7 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Tango.ScreenCapture
{
public class ScreenCaptureEngine : IDisposable
{
private bool _isDisposed;
private Thread _captureThread;
private Bitmap _previousBitmap;
private ImageComparer _comparer;
public event EventHandler<ScreenCaptureFrameReceivedEventArgs> ScreenFrameReceived;
public IScreenCaptureMethod CaptureMethod { get; set; }
public CaptureRegion CaptureRegion { get; set; }
public bool IsStarted { get; set; }
public TimeSpan Interval { get; set; }
public bool CaptureCursor { get; set; }
public bool EnableImageComparison { get; set; }
public ScreenCaptureEngine()
{
Interval = TimeSpan.FromMilliseconds(100);
CaptureMethod = new GdiScreenCapture();
CaptureRegion = new CaptureRegion(System.Windows.Forms.Screen.PrimaryScreen.Bounds);
_comparer = new ImageComparer();
EnableImageComparison = true;
}
public void Start()
{
if (_isDisposed)
{
throw new ObjectDisposedException("Screen capture engine cannot be started after disposed.");
}
if (!IsStarted)
{
IsStarted = true;
_captureThread = new Thread(CaptureThreadMethod);
_captureThread.IsBackground = true;
_captureThread.Name = "Screen Capture Thread";
_captureThread.Start();
}
}
public void Stop()
{
if (IsStarted)
{
IsStarted = false;
}
}
private void CaptureThreadMethod()
{
while (IsStarted)
{
var bitmap = CaptureMethod.GetDesktopBitmap(CaptureRegion);
if (CaptureCursor)
{
using (Graphics g = Graphics.FromImage(bitmap))
{
CursorUtils.ApplyCursor(g, bitmap, CaptureRegion.Left, CaptureRegion.Top);
}
}
if (EnableImageComparison)
{
if (_previousBitmap == null)
{
_previousBitmap = bitmap.Clone() as Bitmap;
OnScreenFrameReceived(new ScreenCaptureFrame(bitmap, null));
}
else
{
var diffBitmap = _comparer.CreateDifferenceBitmap(_previousBitmap, bitmap, Color.Transparent);
_previousBitmap.Dispose();
_previousBitmap = bitmap.Clone() as Bitmap;
OnScreenFrameReceived(new ScreenCaptureFrame(bitmap, diffBitmap));
}
}
else
{
OnScreenFrameReceived(new ScreenCaptureFrame(bitmap, null));
}
Thread.Sleep(Interval);
}
}
public void Dispose()
{
if (!_isDisposed)
{
_isDisposed = true;
Stop();
CaptureMethod?.Dispose();
}
}
protected virtual void OnScreenFrameReceived(ScreenCaptureFrame frame)
{
ScreenFrameReceived?.Invoke(this, new ScreenCaptureFrameReceivedEventArgs()
{
Frame = frame,
});
}
}
}
|