自动截屏工具

本文最后更新于:2019年11月4日 晚上

心路历程

不知道你有没有遇到过这样的情景,老师布置了一个任务,安装一下某个软件,然后让把每一步截图,最后行程报告。
不管你烦不烦,我是很烦这个操作的,安装软件本来就是一项很简单的过程,因为需要时时刻刻的截图,变成了一项很艰巨的任务。

所以我就一直想找一个软件,这个软件的功能是实现自动截图的操作,当然还有几点要求:

  1. 当我按下鼠标左键的时候自动截图,因为每次按下左键都会到下一个界面
  2. 我不想单纯的截一张全屏的图,我想让他截下来当前运行程序的截图。

虽然就只有很少的两个要求,但是并没有发现满足这两个功能的截图软件。

所以我就想写一个这样的软件。

开始操作

要想写一个程序,首先选择的是要用哪一个编程语言。刚开始我选择了java,并且看开发文档写了下面的程序。
他只能实现截屏,然后并不能获取鼠标的状态,同样也就不能直接操作windows的句柄从而获取窗口的截图。

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
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class CaptureScreen {
public static void captureScreen(String folder, String fileName) throws AWTException, IOException {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Rectangle screenRectangle = new Rectangle(screenSize);
Robot robot = new Robot();
BufferedImage image = robot.createScreenCapture(screenRectangle);

File screenFile = new File(folder);
if(!screenFile.exists()) {
screenFile.mkdir();
}
File f = new File(screenFile, fileName);
ImageIO.write(image, "png", f);
if(Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.OPEN)) {
Desktop.getDesktop().open(f);
}
}
public static void main(String[] args){
try {
captureScreen("hello", "11.png");
} catch (AWTException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

然后又找了一个python的代码,然后跟java是同样的问题

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
import time
import win32gui, win32ui, win32con, win32api


def window_capture(filename):
hwnd = 0 # 窗口的编号,0号表示当前活跃窗口
# 根据窗口句柄获取窗口的设备上下文DC(Divice Context)
hwndDC = win32gui.GetWindowDC(hwnd)
# 根据窗口的DC获取mfcDC
mfcDC = win32ui.CreateDCFromHandle(hwndDC)
# mfcDC创建可兼容的DC
saveDC = mfcDC.CreateCompatibleDC()
# 创建bigmap准备保存图片
saveBitMap = win32ui.CreateBitmap()
# 获取监控器信息
MoniterDev = win32api.EnumDisplayMonitors(None, None)
w = MoniterDev[0][2][2]
h = MoniterDev[0][2][3]
# print w,h   #图片大小
# 为bitmap开辟空间
saveBitMap.CreateCompatibleBitmap(mfcDC, w, h)
# 高度saveDC,将截图保存到saveBitmap中
saveDC.SelectObject(saveBitMap)
# 截取从左上角(0,0)长宽为(w,h)的图片
saveDC.BitBlt((0, 0), (w, h), mfcDC, (0, 0), win32con.SRCCOPY)
saveBitMap.SaveBitmapFile(saveDC, filename)


beg = time.time()
for i in range(10):
window_capture("haha.jpg")
end = time.time()
print(end - beg)

没有办法,最终只能选择C语言了,他能直接操作Windows的句柄,并且可以通过hook来获取全局鼠标的状态。

一步一步来,第一个代码先获取一下鼠标的状态,如果我点击鼠标了,让他显示一下我点击了左键还是右键。

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
#include <stdio.h>
#include <windows.h>

HHOOK _glh_hook_ = NULL; //定义为全局变量

LRESULT CALLBACK MouseProc(int nCode, WPARAM wparam, LPARAM lparam)
{
if (nCode >= 0)
{
if(wparam == WM_RBUTTONDOWN)
{
printf("右键");
}
else if (wparam == WM_LBUTTONDOWN)
{
printf("左键");
}
else if (wparam == WM_MBUTTONDOWN)
{
printf("中键");
}
}
return CallNextHookEx(_glh_hook_, nCode, wparam, lparam);
}


int main()
{
HINSTANCE glhInstance = NULL;
glhInstance = GetModuleHandle(NULL);
_glh_hook_ = SetWindowsHookEx(WH_MOUSE_LL, MouseProc, glhInstance, 0);
//WH_MOUSE_LL指监控鼠标行为,MouseProc是回调函数
if(_glh_hook_ == NULL)
{
printf("鼠标钩子获取失败");
}
MSG msg;
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
UnhookWindowsHookEx(_glh_hook_);
return 0;
}

关于全局鼠标钩子卡的原因分析

问题:注册全局钩子后,最大化或关闭时,某些电脑会卡顿,卡的时候不固定,同样的系统有的会卡,有的不会卡。

分析:基于这样的问题进行了大量的资料收集与分析,发现卡的问题其实是在windows 动画上,由于关闭窗口时线程退出消息循环而没结束钩子消息导致都不能接收,于是鼠标消息就在那耗着,直到超时所形成的卡顿现象,解决方案有如下二种:
1,在窗体发送WM_Close消息前先卸载钩子。
2,关闭窗口动画过渡效果,从而减少卡顿时间,比如使用性能模式或使用windows 经典主题。

完整的代码

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
#include "pch.h"
#include <windows.h>
#include <stdint.h>
#include <stdio.h>
#include <iostream>
#include <time.h>
using namespace std;

void ShootScreen(const char* filename, HWND hWnd)
{
HDC hdc = CreateDC("DISPLAY", NULL, NULL, NULL);
int32_t ScrWidth = 0, ScrHeight = 0;
RECT rect = { 0 };
if (hWnd == NULL)
{
ScrWidth = GetDeviceCaps(hdc, HORZRES);
ScrHeight = GetDeviceCaps(hdc, VERTRES);
}
else
{
GetWindowRect(hWnd, &rect);
ScrWidth = rect.right - rect.left;
ScrHeight = rect.bottom - rect.top;
}
HDC hmdc = CreateCompatibleDC(hdc);

HBITMAP hBmpScreen = CreateCompatibleBitmap(hdc, ScrWidth, ScrHeight);
HBITMAP holdbmp = (HBITMAP)SelectObject(hmdc, hBmpScreen);

BITMAP bm;
GetObject(hBmpScreen, sizeof(bm), &bm);

BITMAPINFOHEADER bi = { 0 };
bi.biSize = sizeof(BITMAPINFOHEADER);
bi.biWidth = bm.bmWidth;
bi.biHeight = bm.bmHeight;
bi.biPlanes = bm.bmPlanes;
bi.biBitCount = bm.bmBitsPixel;
bi.biCompression = BI_RGB;
bi.biSizeImage = bm.bmHeight * bm.bmWidthBytes;

char *buf = new char[bi.biSizeImage];
BitBlt(hmdc, 0, 0, ScrWidth, ScrHeight, hdc, rect.left, rect.top, SRCCOPY);
GetDIBits(hmdc, hBmpScreen, 0L, (DWORD)ScrHeight, buf, (LPBITMAPINFO)&bi, (DWORD)DIB_RGB_COLORS);

BITMAPFILEHEADER bfh = { 0 };
bfh.bfType = ((WORD)('M' << 8) | 'B');
bfh.bfSize = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER) + bi.biSizeImage;
bfh.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);
HANDLE hFile = CreateFile(filename, GENERIC_WRITE, 0, 0, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
DWORD dwWrite;
WriteFile(hFile, &bfh, sizeof(BITMAPFILEHEADER), &dwWrite, NULL);
WriteFile(hFile, &bi, sizeof(BITMAPINFOHEADER), &dwWrite, NULL);
WriteFile(hFile, buf, bi.biSizeImage, &dwWrite, NULL);
CloseHandle(hFile);
hBmpScreen = (HBITMAP)SelectObject(hmdc, holdbmp);
}

HHOOK _glh_hook_ = NULL; //定义为全局变量

LRESULT CALLBACK MouseProc(int nCode, WPARAM wparam, LPARAM lparam)
{
if (nCode >= 0)
{
if (wparam == WM_RBUTTONDOWN)
{
printf("右键");
}
else if (wparam == WM_LBUTTONDOWN)
{
printf("左键");
POINT pNow = { 0,0 };
if (GetCursorPos(&pNow)) // 获取鼠标当前位置
{

HWND hwndPointNow = NULL;
hwndPointNow = WindowFromPoint(pNow); // 获取鼠标所在窗口的句柄
if (hwndPointNow)
{
cout << hwndPointNow << endl;
time_t timep;
int t = time(&timep);

char name[256] = { 0 };

sprintf_s(name, 256, "%d.bmp", t);

printf("截图%s\n", name);
ShootScreen(name, hwndPointNow);
}
else
cout << "Error!!" << endl;
}
else
cout << "Error!!" << endl;
}
else if (wparam == WM_MBUTTONDOWN)
{
printf("中键");
}
}
return CallNextHookEx(_glh_hook_, nCode, wparam, lparam);
}

int32_t main()
{
printf("程序运行中");
HINSTANCE glhInstance = NULL;
glhInstance = GetModuleHandle(NULL);
_glh_hook_ = SetWindowsHookEx(WH_MOUSE_LL, MouseProc, glhInstance, 0);
//WH_MOUSE_LL指监控鼠标行为,MouseProc是回调函数
if (_glh_hook_ == NULL)
{
printf("鼠标钩子获取失败");
}
MSG msg;
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
UnhookWindowsHookEx(_glh_hook_);
return 0;

}

但是这个代码是有问题的,Window10的动画冲突,会导致突然电脑变卡

没有办法,最后只能写一个通过按键来截图的工具了,而且进行了完善,可以通过修改配置文件来更改设置信息。

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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
#include "pch.h"
#include <windows.h>
#include <stdint.h>
#include <stdio.h>
#include <iostream>
#include <time.h>
#include <errno.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#include <io.h>
#include <direct.h>
using namespace std;

#define MAX_VALUE 64 /* 定义section,key,value字符串最大长度 */
// printf("File = %s\nLine = %d\nFunc=%s\nDate=%s\nTime=%s\n", __FILE__, __LINE__, __FUNCTION__, __DATE__, __TIME__);
#define PRINT_ERRMSG(STR) fprintf(stderr,"line:%d,msg:%s,eMsg:%s\n", __LINE__, STR, strerror(errno))

typedef struct _option
{
char key[MAX_VALUE]; /* 对应键 */
char value[MAX_VALUE]; /* 对应值 */
struct _option *next; /* 链表连接标识 */
} Option;

typedef struct _data
{
char section[MAX_VALUE]; /* 保存section值 */
Option *option; /* option链表头 */
struct _data *next; /* 链表连接标识 */
} Data;

typedef struct
{
char comment; /* 表示注释的符号 */
char separator; /* 表示分隔符 */
char re_string[MAX_VALUE]; /* 返回值字符串的值 */
int re_int; /* 返回int的值 */
bool re_bool; /* 返回bool的值 */
double re_double; /* 返回double类型 */
Data *data; /* 保存数据的头 */
} Config;

/**
* 判断字符串是否为空
* 为空返回true,不为空返回false
**/
bool str_empty(const char *string)
{
return NULL == string || 0 == strlen(string);
}

/**
* 向链表添加section,key,value
* 如果添加时不存在section则新增一个
* 如果对应section的key不存在则新增一个
* 如果section已存在则不会重复创建
* 如果对应section的key已存在则只会覆盖key的值
**/
bool cnf_add_option(Config *cnf, const char *section, const char *key, const char *value)
{
if (NULL == cnf || str_empty(section) || str_empty(key) || str_empty(value))
{
return false; /* 参数不正确,返回false */
}

Data *p = cnf->data; /* 让变量p循环遍历data,找到对应section */
while (NULL != p && 0 != strcmp(p->section, section))
{
p = p->next;
}

if (NULL == p) /* 说明没有找到section,需要加一个 */
{
Data *ps = (Data*)malloc(sizeof(Data));
if (NULL == ps)
{
exit(-1); /* 申请内存错误 */
}
strcpy(ps->section, section);
ps->option = NULL; /* 初始的option要为空 */
ps->next = cnf->data; /* cnf->data可能为NULL */
cnf->data = p = ps; /* 头插法插入链表 */
}

Option *q = p->option;
while (NULL != q && 0 != strcmp(q->key, key))
{
q = q->next; /* 遍历option,检查key是否已经存在 */
}

if (NULL == q) /* 不存在option,则新建一个 */
{
q = (Option*)malloc(sizeof(Option));
if (NULL == q)
{
exit(-1); /* 申请内存错误 */
}
strcpy(q->key, key);
q->next = p->option; /*这里p->option可能为NULL,不过也没关系 */
p->option = q; /* 头插法插入链表 */
}
strcpy(q->value, value); /* 无论如何要把值改了 */

return true;
}

/**
* 去掉字符串内所有空白
* 且忽略注释部分
* 最终得到没有空白的字符串
**/
bool strip_comments(char *string, char comment)
{
if (NULL == string || '\n' == *string || '\r' == *string)
{
return false; /* 第一个字符为回车或换行,表示空行 */
}

char *p, *q; /* 下面去掉字符串中所有空白字符 */
for (p = q = string; *p != '\0' && *p != comment; p++)
{
if (0 == isspace(*p))
{
*q++ = *p; /* 不是空白字符则重写字符串 */
}
}
*q = '\0';

return 0 != strlen(string); /* 字符串长度不为0,表示数据可用 */
}

/**
* 传递配置文件路径
* 参数有文件路径,注释字符,分隔符
* 返回Config结构体
**/
Config *cnf_read_config(const char *filename, char comment, char separator)
{
Config *cnf = (Config*)malloc(sizeof(Config));
cnf->comment = comment; /* 每一行该字符及以后的字符将丢弃 */
cnf->separator = separator; /* 用来分隔Section 和 数据 */
cnf->data = NULL; /* 初始数据为空 */

if (str_empty(filename))
{
return cnf; /* 空字符串则直接返回对象 */
}

char *p, sLine[MAX_VALUE]; /* 保存一行数据到字符串 */
char section[MAX_VALUE], key[MAX_VALUE], value[MAX_VALUE]; /* 缓存section,key,value */
FILE *fp = fopen(filename, "r");
if (NULL == fp)
{
PRINT_ERRMSG("fopen");
exit(errno); /* 读文件错误直接按照错误码退出 */
}

while (NULL != fgets(sLine, MAX_VALUE, fp))
{
if (strip_comments(sLine, cnf->comment)) /* 去掉字符串所有空白,注释也忽略 */
{
if ('[' == sLine[0] && ']' == sLine[strlen(sLine) - 1])
{
memset(section, '\0', MAX_VALUE); /* 清空section,因为strncpy不追加'\0' */
strncpy(section, sLine + 1, strlen(sLine) - 2);
}
else if (NULL != (p = strchr(sLine, cnf->separator))) /* 存在分隔符 */
{
memset(key, '\0', MAX_VALUE); /* 清空key,因为strncpy不追加'\0' */
strncpy(key, sLine, p - sLine);
strcpy(value, p + 1); /* strcpy会追加'\0',所以妥妥哒 */
cnf_add_option(cnf, section, key, value); /* 添加section,key,value */
} /* 如果该行不存在分隔符则忽略这一行 */
} /* end strip_comments */
} /* end while */

fclose(fp);
return cnf;
}

/**
* 获取指定类型的值
* 根据不同类型会赋值给对应值
* 本方法需要注意,int和double的转换,不满足就是0
* 需要自己写代码时判断好
**/
bool cnf_get_value(Config *cnf, const char *section, const char *key)
{
Data *p = cnf->data; /* 让变量p循环遍历data,找到对应section */
while (NULL != p && 0 != strcmp(p->section, section))
{
p = p->next;
}

if (NULL == p)
{
PRINT_ERRMSG("section not find!");
return false;
}

Option *q = p->option;
while (NULL != q && 0 != strcmp(q->key, key))
{
q = q->next; /* 遍历option,检查key是否已经存在 */
}

if (NULL == q)
{
PRINT_ERRMSG("key not find!");
return false;
}

strcpy(cnf->re_string, q->value); /* 将结果字符串赋值 */
cnf->re_int = atoi(cnf->re_string); /* 转换为整形 */
cnf->re_bool = 0 == strcmp("true", cnf->re_string); /* 转换为bool型 */
cnf->re_double = atof(cnf->re_string); /* 转换为double型 */

return true;
}

/**
* 判断section是否存在
* 不存在返回空指针
* 存在则返回包含那个section的Data指针
**/
Data *cnf_has_section(Config *cnf, const char *section)
{
Data *p = cnf->data; /* 让变量p循环遍历data,找到对应section */
while (NULL != p && 0 != strcmp(p->section, section))
{
p = p->next;
}

if (NULL == p) /* 没找到则不存在 */
{
return NULL;
}

return p;
}

/**
* 判断指定option是否存在
* 不存在返回空指针
* 存在则返回包含那个section下key的Option指针
**/
Option *cnf_has_option(Config *cnf, const char *section, const char *key)
{
Data *p = cnf_has_section(cnf, section);
if (NULL == p) /* 没找到则不存在 */
{
return NULL;
}

Option *q = p->option;
while (NULL != q && 0 != strcmp(q->key, key))
{
q = q->next; /* 遍历option,检查key是否已经存在 */
}
if (NULL == q) /* 没找到则不存在 */
{
return NULL;
}

return q;
}

/**
* 将Config对象写入指定文件中
* header表示在文件开头加一句注释
* 写入成功则返回true
**/
bool cnf_write_file(Config *cnf, const char *filename, const char *header)
{
FILE *fp = fopen(filename, "w");
if (NULL == fp)
{
PRINT_ERRMSG("fopen");
exit(errno); /* 读文件错误直接按照错误码退出 */
}

if (0 < strlen(header)) /* 文件注释不为空,则写注释到文件 */
{
fprintf(fp, "%c %s\n\n", cnf->comment, header);
}

Option *q;
Data *p = cnf->data;
while (NULL != p)
{
fprintf(fp, "[%s]\n", p->section);
q = p->option;
while (NULL != q)
{
fprintf(fp, "%s %c %s\n", q->key, cnf->separator, q->value);
q = q->next;
}
p = p->next;
}

fclose(fp);
return true;
}

/**
* 删除option
**/
bool cnf_remove_option(Config *cnf, const char *section, const char *key)
{
Data *ps = cnf_has_section(cnf, section);
if (NULL == ps) /* 没找到则不存在 */
{
return NULL;
}

Option *p, *q;
q = p = ps->option;
while (NULL != p && 0 != strcmp(p->key, key))
{
if (p != q)
{
q = q->next; /* 始终让q处于p的上一个节点 */
}
p = p->next;
}

if (NULL == p) /* 没找到则不存在 */
{
return NULL;
}

if (p == q) /* 第一个option就匹配了 */
{
ps->option = p->next;
}
else
{
q->next = p->next;
}

free(p);
q = p = NULL; // 避免野指针

return true;
}

/**
* 删除section
**/
bool cnf_remove_section(Config *cnf, const char *section)
{
if (str_empty(section))
{
return false;
}

Data *p, *q;
q = p = cnf->data; /* 让变量p循环遍历data,找到对应section */
while (NULL != p && 0 != strcmp(p->section, section))
{
if (p != q)
{
q = q->next; /* 始终让q处于p的上一个节点 */
}
p = p->next;
}

if (NULL == p) /* 没有找到section */
{
return false;
}

if (p == q) /* 这里表示第一个section,因此链表头位置改变 */
{
cnf->data = p->next;
}
else /* 此时是中间或尾部节点 */
{
q->next = p->next;
}

Option *o = p->option;
while (NULL != o)
{
free(o); /* 循环释放所有option */
o = o->next;
}
p->option = NULL; // 避免野指针
free(p); /* 释放删除的section */
q = p = NULL; // 避免野指针

return true;
}

/**
* 打印当前Config对象
**/
void print_config(Config *cnf)
{
Data *p = cnf->data; // 循环打印结果
while (NULL != p)
{
printf("[%s]\n", p->section);

Option *q = p->option;
while (NULL != q)
{
printf(" %s %c %s\n", q->key, cnf->separator, q->value);
q = q->next;
}
p = p->next;
}
}

char preName[255];
double scale = 1.0;
void ShootScreen(const char* filename, HWND hWnd)
{
HDC hdc = CreateDC("DISPLAY", NULL, NULL, NULL);
int32_t ScrWidth = 0, ScrHeight = 0;
RECT rect = { 0 };
if (hWnd == NULL)
{
ScrWidth = GetDeviceCaps(hdc, HORZRES);
ScrHeight = GetDeviceCaps(hdc, VERTRES);
}
else
{
GetWindowRect(hWnd, &rect);
ScrWidth = (rect.right * scale - rect.left * scale) ;
ScrHeight = (rect.bottom * scale - rect.top * scale);
}
HDC hmdc = CreateCompatibleDC(hdc);

HBITMAP hBmpScreen = CreateCompatibleBitmap(hdc, ScrWidth, ScrHeight);
HBITMAP holdbmp = (HBITMAP)SelectObject(hmdc, hBmpScreen);

BITMAP bm;
GetObject(hBmpScreen, sizeof(bm), &bm);

BITMAPINFOHEADER bi = { 0 };
bi.biSize = sizeof(BITMAPINFOHEADER);
bi.biWidth = bm.bmWidth;
bi.biHeight = bm.bmHeight;
bi.biPlanes = bm.bmPlanes;
bi.biBitCount = bm.bmBitsPixel;
bi.biCompression = BI_RGB;
bi.biSizeImage = bm.bmHeight * bm.bmWidthBytes;

char *buf = new char[bi.biSizeImage];
BitBlt(hmdc, 0, 0, ScrWidth, ScrHeight, hdc, rect.left * scale, rect.top * scale, SRCCOPY);
GetDIBits(hmdc, hBmpScreen, 0L, (DWORD)ScrHeight, buf, (LPBITMAPINFO)&bi, (DWORD)DIB_RGB_COLORS);

BITMAPFILEHEADER bfh = { 0 };
bfh.bfType = ((WORD)('M' << 8) | 'B');
bfh.bfSize = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER) + bi.biSizeImage;
bfh.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);
HANDLE hFile = CreateFile(filename, GENERIC_WRITE, 0, 0, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
DWORD dwWrite;
WriteFile(hFile, &bfh, sizeof(BITMAPFILEHEADER), &dwWrite, NULL);
WriteFile(hFile, &bi, sizeof(BITMAPINFOHEADER), &dwWrite, NULL);
WriteFile(hFile, buf, bi.biSizeImage, &dwWrite, NULL);
CloseHandle(hFile);
hBmpScreen = (HBITMAP)SelectObject(hmdc, holdbmp);
}

HHOOK g_kb_hook = NULL;
int keyCode = 0;
LRESULT CALLBACK kb_proc(int code, WPARAM w, LPARAM lparam)
{
PKBDLLHOOKSTRUCT p = (PKBDLLHOOKSTRUCT)lparam;
if (w == WM_KEYDOWN)
{
cout << "你按下了键盘码为:" << p->vkCode << "的键" << endl;
if (p->vkCode == keyCode)
{
//POINT pNow = { 0,0 };
//if (GetCursorPos(&pNow)) // 获取鼠标当前位置
//{
HWND hwndPointNow = NULL;
//hwndPointNow = WindowFromPoint(pNow); // 获取鼠标所在窗口的句柄
//hwndPointNow = GetActiveWindow();
hwndPointNow = GetForegroundWindow();

//cout << hwndPointNow << endl;
if (hwndPointNow)
{
//cout << hwndPointNow << endl;
time_t timep;
int t = time(&timep);
static int preT = 0;
static int cnt = 0;
if (preT == t) {
cnt++;
}
else {
cnt = 0;
}
char name[256] = { 0 };

sprintf_s(name, 256, "%s/%d%d.bmp", preName, t, cnt);
preT = t;

printf("[截图捕获成功,名称为:%s]\n", name);
ShootScreen(name, hwndPointNow);
}
else
{
cout << "Error!!" << endl;
}
}
}
return CallNextHookEx(g_kb_hook, code, w, lparam);
}


int32_t main()
{
char fileName[] = "config.ini";

FILE *fp = fopen(fileName, "r");
Config *cnf = NULL;
if (fp == NULL)
{
cnf = new Config();
cnf->comment = '#';
cnf->separator = '=';

cnf_add_option(cnf, "config", "keyboard", "162"); // 新增NEW下的new_1的值
cnf_add_option(cnf, "config", "scale", "1.25"); // 新增NEW下的new_1的值
}
else
{
cnf = cnf_read_config(fileName, '#', '=');
}
if(fp != NULL)
fclose(fp);
if (NULL == cnf)
{
return -1; /* 创建对象失败 */
}

cnf_get_value(cnf, "config", "keyboard"); // 获取NEW1下的new_2值
keyCode = cnf->re_int;
cnf_get_value(cnf, "config", "scale"); // 获取NEW1下的new_2值
scale = cnf->re_double;
//printf("%d %f\n", key, scale);
//printf("cnf_get_value:%s,%d,%d,%f\n",cnf->re_string,cnf->re_int,cnf->re_bool,cnf->re_double);

//cnf->separator = ':'; // 将分隔符改成 : ,冒号
cnf_write_file(cnf, fileName, "这是一个配置文件,keyboard表示截屏的快捷键,scale表示WIN10屏幕缩放的比例(右键桌面->显示设置->缩放与布局)"); // 将对象写入cnf_new.ini文件
printf("============================================================================================\n");
printf("说明:\n");
printf("这是一个方便大量截图的工具,只需要按键盘上的一个键,就可以很轻松的捕获当前活动窗口的截图\n");
printf("默认截图按键是Ctrl,键盘代码是162,如果想要更改,请打开软件同目录下的config.ini\n");
printf("Win10有一个缩放与布局,如果截图与想要的不符,请修改config.ini下面的scale属性,默认是1.25\n");
printf("============================================================================================\n");
printf("为本次的截图任务起一个名字吧(请不能要含特殊符号):");
cin >> preName;
// 文件夹不存在则创建文件夹
if (_access(preName, 0) == -1)
{
_mkdir(preName);
}

printf("开始截图,每当你按下对应按键的时候,都会产生鼠标下窗口的一张图片\n");

HINSTANCE glhInstance = NULL;
glhInstance = GetModuleHandle(NULL);
g_kb_hook = SetWindowsHookEx(WH_KEYBOARD_LL, &kb_proc, glhInstance, 0);
if (g_kb_hook == NULL)
{
printf("SetWindowsHookEx error!");
exit(0);
}
MSG msg;
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
UnhookWindowsHookEx(g_kb_hook);
return 0;

}