问题分析
最近一直上网课,实在不知道孩子在干嘛,忍不住想监控孩子屏幕看看孩子在干嘛。网上有虽然有很多软件,但是总是不满意,(1)有界面,不能无感截屏(2)有的截屏时间属于连续截屏,资源占用高。(3)软件占用空间太。虽然一直没有实际安装到孩子电脑上,但是想想技术实现也行。
需求确定
基本需求
(1)定时器定时调用截屏 (2)隐藏窗口(3)自动启动(4)调用截屏
其他需求
(1)程序小巧简单,准备使用 避免python 之类c++。(2)增加特定时间段不截屏的功能。(3)视频生成?快速浏览?
解决方案
语言选择:最熟悉C++,依赖库少
(1)定时器:
参考 C+CGitHub - collielimabean/Timer: Simple timer that on expiration executes a callback.
示例代码
void Callback()
{
time_t current = time(nullptr);
std::cout << "Callback executed on " << std::ctime(¤t) << std::endl;
}
int main()
{
Timer t(Interval(2000), &Callback, true);
t.Start();
}
(2)截屏软件:
snapaste 属于开源绿色软件,支持命令行截图,可以参考相关命令
c++ 截屏也很简单 参考 C++实现截图截屏的示例代码-云海天教程
本文直接使用下面截屏代码
#include "Timer.h"
#include <ctime>
#include <iostream>
#include"windows.h"
#include <atlimage.h>
#include <iomanip>
#include <string>
#include <sstream>
#define UNICODE
#ifndef ULONG_PTR
#define ULONG_PTR unsigned long*
#endif
using namespace std;
#include "GdiPlus.h"
using namespace Gdiplus;
#pragma comment(lib, "gdiplus.lib")
string SavePath = "e:\\";
void CaptureScreen()
{
string stime;
char tAll[255];
auto tm = *std::localtime(&t);
strftime(tAll, sizeof(tAll), "%Y-%m-%d-%H-%M-%S", &tm);
stime = tAll;
//capture screen
HDC hdcSrc = GetDC(NULL);
int nBitPerPixel = GetDeviceCaps(hdcSrc, BITSPIXEL);
//int nWidth = GetDeviceCaps(hdcSrc, HORZRES);
//int nHeight = GetDeviceCaps(hdcSrc, VERTRES);
//高分屏需要获取不同参数
int nWidth = GetDeviceCaps(hdcSrc, DESKTOPHORZRES);
int nHeight = GetDeviceCaps(hdcSrc, DESKTOPVERTRES);
CImage image;
image.Create(nWidth, nHeight, nBitPerPixel);
BitBlt(image.GetDC(), 0, 0, nWidth, nHeight, hdcSrc, 0, 0, SRCCOPY);
ReleaseDC(NULL, hdcSrc);
image.ReleaseDC();
string FileName = SavePath + "Save"+ stime+".JPG";
image.Save(FileName.c_str(), Gdiplus::ImageFormatJPEG);
}
(3)后台执行c++ 让程序消失并后台运行 开机自动启动_Lo问我为什么看星星的博客-CSDN博客_c++ 锁定鼠标
需要代码
HWND hWnd = GetConsoleWindow();
int SetAutoRun() {
LPCTSTR lpSubKey = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run";
HKEY hKey;
REGSAM flag = KEY_WOW64_64KEY;
DWORD dwDisposition = REG_OPENED_EXISTING_KEY;
LONG lRet = RegOpenKeyEx(HKEY_LOCAL_MACHINE, lpSubKey, 0, KEY_ALL_ACCESS | flag, &hKey);
if (ERROR_SUCCESS != lRet) return -1;
char ExeFile[200];
GetModuleFileName(NULL, ExeFile, 200);
TCHAR* pchrName = ExeFile;
lRet = ::RegSetValueEx(hKey, TEXT("后台截屏"), NULL, REG_SZ, (LPBYTE)pchrName, strlen(pchrName) * sizeof(TCHAR) + 1);
if (ERROR_SUCCESS != lRet) return -1;
::RegCloseKey(hKey);
return 0;
}
int main()
{
SetAutoRun();
int minute = 2; //间隔1分钟
int second = minute * 60;
long TimeSpan = 1000 * second;
Timer t(Interval(TimeSpan), &CaptureScreen, true);
t.Start();
ShowWindow(hWnd, SW_HIDE);
getch(); //不然一消失程序就结束了
return 0;
}
VS2019 编译 完美运行。需要注意保存路径默认在e:\ ,发布时,注意需要gdiplus 库。
其他时间匹配以及保存路径 都可以写一个配置文件予以解决。
使用cereal 库 实现了json 配置文件读取,时间匹配也完成。