forked from gavinkendall/autoscreen
/
ScreenCapture.cs
375 lines (303 loc) · 13.7 KB
/
ScreenCapture.cs
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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
//-----------------------------------------------------------------------
// <copyright file="ScreenCapture.cs" company="Gavin Kendall">
// Copyright (c) Gavin Kendall. All rights reserved.
// </copyright>
// <author>Gavin Kendall</author>
// <summary></summary>
//-----------------------------------------------------------------------
namespace AutoScreenCapture
{
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;
public class ScreenCapture
{
[StructLayout(LayoutKind.Sequential)]
private struct CURSORINFO
{
public Int32 cbSize;
public Int32 flags;
public IntPtr hCursor;
public POINTAPI ptScreenPos;
}
[StructLayout(LayoutKind.Sequential)]
private struct POINTAPI
{
public int x;
public int y;
}
[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
private static extern void GetWindowRect(IntPtr hWnd, out Rectangle rect);
[DllImport("user32.dll")]
private static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);
[DllImport("user32.dll")]
public static extern IntPtr GetWindowThreadProcessId(IntPtr hWnd, out uint ProcessId);
[DllImport("user32.dll")]
private static extern bool GetCursorInfo(out CURSORINFO pci);
[DllImport("user32.dll", SetLastError = true)]
private static extern bool DrawIconEx(IntPtr hdc, int xLeft, int yTop, IntPtr hIcon, int cxWidth, int cyHeight, int istepIfAniCur, IntPtr hbrFlickerFreeDraw, int diFlags);
private const Int32 CURSOR_SHOWING = 0x0001;
private const Int32 DI_NORMAL = 0x0003;
public const int CAPTURE_LIMIT_MIN = 1;
public const int CAPTURE_LIMIT_MAX = 9999;
private const double MIN_FREE_DISK_SPACE_PERCENTAGE = 3;
/// <summary>
/// The default image format.
/// </summary>
public const string DefaultImageFormat = ImageFormatSpec.NAME_JPEG;
private const int MAX_CHARS = 48000;
private const int IMAGE_RESOLUTION_RATIO_MIN = 1;
public const int IMAGE_RESOLUTION_RATIO_MAX = 100;
public int Delay { get; set; }
public int Limit { get; set; }
public int Count { get; set; }
public bool RunningFromCommandLine { get; set; }
public static bool LockScreenCaptureSession { get; set; }
public bool Running { get; set; }
/// <summary>
/// The date/time when the user started a screen capture session.
/// </summary>
public DateTime DateTimeStartCapture { get; set; }
/// <summary>
/// The date/time when screenshots are taken (or when the previous screenshots were taken).
/// </summary>
public DateTime DateTimePreviousCycle { get; set; }
/// <summary>
/// The date/time of the next screen capture cycle.
/// If we're still waiting for the very first screenshots to be taken then calculate from the date/time when the user started a screen capture session
/// otherwise calculate from the date/time when the previous screenshots were taken.
/// </summary>
public DateTime DateTimeNextCycle { get { return DateTimePreviousCycle.Ticks == 0 ? DateTimeStartCapture.AddMilliseconds(Delay) : DateTimePreviousCycle.AddMilliseconds(Delay); } }
/// <summary>
/// The time remaining between now and the next screenshot that will be taken.
/// </summary>
public TimeSpan TimeRemainingForNextScreenshot { get { return DateTimeNextCycle.Subtract(DateTime.Now).Duration(); } }
/// <summary>
/// The title of the active window.
/// </summary>
public string ActiveWindowTitle { get; set; }
public string ActiveWindowProcessName { get; set; }
public Image GetImageByPath(string path)
{
Image image = null;
if (!string.IsNullOrEmpty(path) && File.Exists(path))
{
using (FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read))
{
image = Image.FromStream(stream);
}
}
GC.Collect();
return image;
}
public Bitmap GetScreenBitmap(int x, int y, int width, int height, int resolutionRatio, bool mouse)
{
try
{
if (width > 0 && height > 0)
{
Size blockRegionSize = new Size(width, height);
if (resolutionRatio < IMAGE_RESOLUTION_RATIO_MIN || resolutionRatio > IMAGE_RESOLUTION_RATIO_MAX)
{
resolutionRatio = 100;
}
float imageResolutionRatio = (float)resolutionRatio / 100;
int destinationWidth = (int)(width * imageResolutionRatio);
int destinationHeight = (int)(height * imageResolutionRatio);
Bitmap bitmapSource = new Bitmap(width, height);
Graphics graphicsSource = Graphics.FromImage(bitmapSource);
graphicsSource.CopyFromScreen(x, y, 0, 0, blockRegionSize, CopyPixelOperation.SourceCopy);
if (mouse)
{
CURSORINFO pci;
pci.cbSize = Marshal.SizeOf(typeof(CURSORINFO));
if (GetCursorInfo(out pci))
{
if (pci.flags == CURSOR_SHOWING)
{
var hdc = graphicsSource.GetHdc();
DrawIconEx(hdc, pci.ptScreenPos.x - x, pci.ptScreenPos.y - y, pci.hCursor, 0, 0, 0, IntPtr.Zero, DI_NORMAL);
graphicsSource.ReleaseHdc();
}
}
}
Bitmap bitmapDestination = new Bitmap(destinationWidth, destinationHeight);
Graphics graphicsDestination = Graphics.FromImage(bitmapDestination);
graphicsDestination.DrawImage(bitmapSource, 0, 0, destinationWidth, destinationHeight);
graphicsSource.Flush();
graphicsDestination.Flush();
GC.Collect();
return bitmapDestination;
}
return null;
}
catch (Exception ex)
{
// Don't log an error if Windows is locked at the time a screenshot was taken.
if (!ex.Message.Equals("The handle is invalid"))
{
Log.Write("ScreenCapture::GetScreenBitmap", ex);
}
return null;
}
}
public Bitmap GetActiveWindowBitmap()
{
try
{
Rectangle rect;
GetWindowRect(GetForegroundWindow(), out rect);
int width = rect.Width - rect.X;
int height = rect.Height - rect.Y;
if (width > 0 && height > 0)
{
Bitmap bitmap = new Bitmap(width, height);
Graphics graphics = Graphics.FromImage(bitmap);
graphics.CopyFromScreen(new Point(rect.X, rect.Y), new Point(0, 0), new Size(width, height));
GC.Collect();
return bitmap;
}
return null;
}
catch (Exception ex)
{
// Don't log an error if Windows is locked at the time a screenshot was taken.
if (!ex.Message.Equals("The handle is invalid"))
{
Log.Write("ScreenCapture::GetScreenBitmap", ex);
}
return null;
}
}
public string GetActiveWindowTitle()
{
IntPtr handle;
int chars = MAX_CHARS;
StringBuilder buffer = new StringBuilder(chars);
handle = GetForegroundWindow();
if (GetWindowText(handle, buffer, chars) > 0)
{
// Make sure to strip out the backslash if it's in the window title.
return buffer.ToString().Replace(@"\", string.Empty);
}
return "(system)";
}
public string GetActiveWindowProcessName()
{
IntPtr hwnd = GetForegroundWindow();
uint pid;
GetWindowThreadProcessId(hwnd, out pid);
Process p = Process.GetProcessById((int)pid);
return p.ProcessName;
}
public bool GetScreenImages(int component, int x, int y, int width, int height, bool mouse, int resolutionRatio, out Bitmap bitmap)
{
bitmap = component == 0
? GetActiveWindowBitmap()
: GetScreenBitmap(x, y, width, height, resolutionRatio, mouse);
GC.Collect();
if (bitmap != null)
{
return true;
}
return false;
}
public bool TakeScreenshot(string path, ImageFormat format, int component, ScreenshotType screenshotType,
int jpegQuality, Guid viewId, Bitmap bitmap, string label, string windowTitle, string processName,
ScreenCollection screenCollection, RegionCollection regionCollection, ScreenshotCollection screenshotCollection)
{
try
{
if (!string.IsNullOrEmpty(path))
{
Log.Write("Attempting to write image to file at path \"" + path + "\"");
FileInfo fileInfo = new FileInfo(path);
if (fileInfo.Directory != null && fileInfo.Directory.Root.Exists)
{
DriveInfo driveInfo = new DriveInfo(fileInfo.Directory.Root.FullName);
if (driveInfo.IsReady)
{
double freeDiskSpacePercentage = (driveInfo.AvailableFreeSpace / (float) driveInfo.TotalSize) * 100;
Log.Write("Percentage of free disk space on drive " + fileInfo.Directory.Root.FullName + " is " + (int)freeDiskSpacePercentage + "%");
if (freeDiskSpacePercentage > MIN_FREE_DISK_SPACE_PERCENTAGE)
{
string dirName = Path.GetDirectoryName(path);
if (!string.IsNullOrEmpty(dirName))
{
if (!Directory.Exists(dirName))
{
Directory.CreateDirectory(dirName);
Log.Write("Directory \"" + dirName + "\" did not exist so it was created");
}
screenshotCollection.Add(new Screenshot(DateTimePreviousCycle, path, format, component, screenshotType, windowTitle, processName, viewId, label));
SaveToFile(path, format, jpegQuality, bitmap);
}
}
else
{
Log.Write($"ERROR: Unable to save screenshot due to lack of available disk space on drive {fileInfo.Directory.Root.FullName} so screen capture session is being stopped");
return false;
}
}
else
{
Log.Write("WARNING: Unable to save screenshot. Drive not ready");
}
}
else
{
Log.Write("WARNING: Unable to save screenshot. Directory root does not exist");
}
}
else
{
Log.Write("No path available");
return false;
}
return true;
}
catch (Exception ex)
{
Log.Write("ScreenCapture::TakeScreenshot", ex);
return false;
}
}
private void SaveToFile(string path, ImageFormat format, int jpegQuality, Bitmap bitmap)
{
try
{
if (bitmap != null && format != null && !string.IsNullOrEmpty(path))
{
if (format.Name.Equals(ImageFormatSpec.NAME_JPEG))
{
var encoderParams = new EncoderParameters(1);
encoderParams.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, jpegQuality);
var encoderInfo = GetEncoderInfo("image/jpeg");
bitmap.Save(path, encoderInfo, encoderParams);
}
else
{
bitmap.Save(path, format.Format);
}
Log.Write("Screenshot saved to file at path \"" + path + "\"");
}
}
catch (Exception ex)
{
Log.Write("ScreenCapture::SaveToFile", ex);
}
}
private ImageCodecInfo GetEncoderInfo(string mimeType)
{
var encoders = ImageCodecInfo.GetImageEncoders();
return encoders.FirstOrDefault(t => t.MimeType == mimeType);
}
}
}