这几天爱人老是迷在游戏上,一坐电脑前就是几个小时,还怪我没提醒她休息下,有口难辩,趁她休息时间,给她电脑上个提醒小程序。
思路很简单,做一个小服务,随开机运行,然后设定时间间隔,到点就来个屏保或锁屏啥的,生成的服务screensaver.exe ;
可以通过管理员身份启动命令行,进入所在目录,运行screensaver.exe install安装服务和screensaver.exe delete移除服务,以下是示列代码,分享给那些有需求的小伙伴们,大家可以按自己需求自由发挥
示例代码:
/*
计算机使用护眼服务[windows],2017-04-02,py_free
*/
#include <windows.h>
#include <tchar.h>
#include <strsafe.h>
#include <time.h>
#include <string>
//服务名
#define SVCNAME TEXT("screen_saver")
namespace G_VALUE{
unsigned int timeL = 3600;//时间间隔(s),默认1小时
unsigned int cmdType=3;//
std::string scrCMD="Mystify.scr /s";//启动屏保命令[Mystify.scr为屏保程序]
std::string pcfgCMD="rundll32.exe powrProf.dll,SetSuspendState";//系统睡眠命令
std::string lockCMD="rundll32.exe user32.dll,LockWorkStation";//锁定计算机
};
//服务相关全局变量
SERVICE_STATUS gSvcStatus;
SERVICE_STATUS_HANDLE gSvcStatusHandle;
HANDLE ghSvcStopEvent = NULL;
HANDLE m_HThread;
DWORD m_dwThreadID;
BOOL m_bRun = FALSE;
int myApp();
//服务安装卸载相关
VOID SvcInstall(void);
VOID DoDeleteSvc(void);
VOID WINAPI SvcCtrlHandler( DWORD );
VOID WINAPI SvcMain( DWORD, LPTSTR * );
VOID ReportSvcStatus( DWORD, DWORD, DWORD );
VOID SvcInit( DWORD, LPTSTR * );
VOID SvcReportEvent( LPTSTR );
VOID CALLBACK MainThread(HWND hwnd,UINT uMsg,UINT_PTR idEvent,DWORD dwTime);
//
void getConf();
//入口函数
void __cdecl _tmain(int argc, TCHAR *argv[])
{
// If command-line parameter is "install", install the service.
// Otherwise, the service is probably being started by the SCM.
#ifdef _UNICODE
printf_s("_UNICODE \n");
#endif
if( lstrcmpi( argv[1], TEXT("-h")) == 0 ){
printf_s("[1]-h 帮助\n[2]install 安装服务\n[3]delete 移除服务\n");
return;
}
if( lstrcmpi( argv[1], TEXT("install")) == 0 )
{
SvcInstall();
return;
}
else if( lstrcmpi( argv[1], TEXT("delete")) == 0 )
{
DoDeleteSvc();
return;
}
// TO_DO: Add any additional services for the process to this table.
SERVICE_TABLE_ENTRY DispatchTable[] =
{
{ SVCNAME, (LPSERVICE_MAIN_FUNCTION) SvcMain },
{ NULL, NULL }
};
// This call returns when the service has stopped.
// The process should simply terminate when the call returns.
m_bRun = TRUE;
if (!StartServiceCtrlDispatcher( DispatchTable ))
{
SvcReportEvent(TEXT("StartServiceCtrlDispatcher"));
myApp();
MSG msg;
while (GetMessage(&msg, 0, 0, 0))
DispatchMessage(&msg);
}
};
int myApp()
{
getConf();
unsigned int runT=time(NULL)+G_VALUE::timeL;
for(;;){
if(runT<time(NULL)){
switch(G_VALUE::cmdType){
case 1:
system(G_VALUE::scrCMD.c_str());break;
case 2:
system(G_VALUE::pcfgCMD.c_str());break;
case 3:
system(G_VALUE::lockCMD.c_str());
break;
default:
system(G_VALUE::lockCMD.c_str());
break;
}
runT=time(NULL)+G_VALUE::timeL;
}
::Sleep(100);
}
return 0;
};
//
VOID SvcInstall()
{
SC_HANDLE schSCManager;
SC_HANDLE schService;
TCHAR szPath[MAX_PATH];
if( !GetModuleFileName( NULL, szPath, MAX_PATH ) )
{
printf_s("安装服务失败 (%d)! \n",GetLastError());
return;
}
// Get a handle to the SCM database.
schSCManager = OpenSCManager(
NULL, // local computer
NULL, // ServicesActive database
SC_MANAGER_ALL_ACCESS); // full access rights
if (NULL == schSCManager)
{
printf_s("打开服务管理器失败 (%d)! \n",GetLastError());
return;
}
// Create the service
schService = CreateService(
schSCManager, // SCM database
SVCNAME, // name of service
SVCNAME, // service name to display
SERVICE_ALL_ACCESS, // desired access
SERVICE_WIN32_OWN_PROCESS, // service type
SERVICE_AUTO_START, // start type
SERVICE_ERROR_NORMAL, // error control type
szPath, // path to service's binary
NULL, // no load ordering group
NULL, // no tag identifier
NULL, // no dependencies
NULL, // LocalSystem account
NULL); // no password
if (schService == NULL)
{
printf_s("创建服务失败 (%d)! \n",GetLastError());
CloseServiceHandle(schSCManager);
return;
}else {
printf_s("\r\n~~~~~~~~~~~~~~~~~~~~~\r\n 屏幕保护服务安装成功\r\n~~~~~~~~~~~~~~~~~~~~~\r\n");
}
CloseServiceHandle(schService);
CloseServiceHandle(schSCManager);
};
VOID DoDeleteSvc()
{
SC_HANDLE schSCManager;
SC_HANDLE schService;
//SERVICE_STATUS ssStatus;
// Get a handle to the SCM database.
schSCManager = OpenSCManager(
NULL, // local computer
NULL, // ServicesActive database
SC_MANAGER_ALL_ACCESS); // full access rights
if (NULL == schSCManager)
{
printf_s("打开服务管理器失败 (%d)! \n",GetLastError());
return;
}
// Get a handle to the service.
schService = OpenService(
schSCManager, // SCM database
SVCNAME, // name of service
DELETE); // need delete access
if (schService == NULL)
{
printf_s("获取服务失败 (%d)! \n",GetLastError());
CloseServiceHandle(schSCManager);
return;
}
// Delete the service.
if (! DeleteService(schService) )
{
printf_s("删除服务失败 (%d)! \n",GetLastError());
}
else {
printf_s("服务成功移除 ! \n");
}
CloseServiceHandle(schService);
CloseServiceHandle(schSCManager);
}
//
VOID WINAPI SvcMain( DWORD dwArgc, LPTSTR *lpszArgv )
{
// Register the handler function for the service
gSvcStatusHandle = RegisterServiceCtrlHandler(
SVCNAME,
SvcCtrlHandler);
if( !gSvcStatusHandle )
{
SvcReportEvent(TEXT("RegisterServiceCtrlHandler"));
return;
}
// These SERVICE_STATUS members remain as set here
gSvcStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
gSvcStatus.dwServiceSpecificExitCode = 0;
// Report initial status to the SCM
ReportSvcStatus( SERVICE_START_PENDING, NO_ERROR, 3000 );
// Perform service-specific initialization and work.
SvcInit( dwArgc, lpszArgv );
};
//
VOID SvcInit( DWORD /*dwArgc*/, LPTSTR* /*lpszArgv*/)
{
// TO_DO: Declare and set any required variables.
// Be sure to periodically call ReportSvcStatus() with
// SERVICE_START_PENDING. If initialization fails, call
// ReportSvcStatus with SERVICE_STOPPED.
// Create an event. The control handler function, SvcCtrlHandler,
// signals this event when it receives the stop control code.
TCHAR szPath[MAX_PATH];
GetModuleFileName( NULL, szPath, MAX_PATH );
TCHAR drive[MAX_PATH],dir[MAX_PATH],fname[MAX_PATH],ext[MAX_PATH];
_tsplitpath_s( szPath,drive,dir,fname,ext );
strcpy_s( szPath,MAX_PATH, drive );
strcat_s( szPath,MAX_PATH, dir );
SetCurrentDirectory( szPath );
ghSvcStopEvent = CreateEvent(
NULL, // default security attributes
TRUE, // manual reset event
FALSE, // not signaled
NULL); // no name
if ( ghSvcStopEvent == NULL)
{
ReportSvcStatus( SERVICE_STOPPED, NO_ERROR, 0 );
return;
}
m_HThread = CreateThread( (LPSECURITY_ATTRIBUTES)NULL, 0, (LPTHREAD_START_ROUTINE)MainThread, 0, 0, &m_dwThreadID);
if( m_HThread != NULL )
{
m_bRun = TRUE;
}
// Report running status when initialization is complete.
ReportSvcStatus( SERVICE_RUNNING, NO_ERROR, 0 );
bool bWriteFlag = false;
while(1)
{
// Check whether to stop the service.
WaitForSingleObject(ghSvcStopEvent, INFINITE);
if(!bWriteFlag)
{
printf_s("监听服务正常停止!\n");
bWriteFlag = true;
}
m_bRun = FALSE;
ReportSvcStatus( SERVICE_STOPPED, NO_ERROR, 0 );
}
};
//
VOID ReportSvcStatus( DWORD dwCurrentState,
DWORD dwWin32ExitCode,
DWORD dwWaitHint)
{
static DWORD dwCheckPoint = 1;
// Fill in the SERVICE_STATUS structure.
gSvcStatus.dwCurrentState = dwCurrentState;
gSvcStatus.dwWin32ExitCode = dwWin32ExitCode;
gSvcStatus.dwWaitHint = dwWaitHint;
if (dwCurrentState == SERVICE_START_PENDING)
gSvcStatus.dwControlsAccepted = 0;
else gSvcStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP;
if ( (dwCurrentState == SERVICE_RUNNING) ||
(dwCurrentState == SERVICE_STOPPED) )
gSvcStatus.dwCheckPoint = 0;
else gSvcStatus.dwCheckPoint = dwCheckPoint++;
// Report the status of the service to the SCM.
SetServiceStatus( gSvcStatusHandle, &gSvcStatus );
}
//
VOID WINAPI SvcCtrlHandler( DWORD dwCtrl )
{
// Handle the requested control code.
switch(dwCtrl)
{
case SERVICE_CONTROL_STOP:
ReportSvcStatus(SERVICE_STOP_PENDING, NO_ERROR, 0);
// Signal the service to stop.
SetEvent(ghSvcStopEvent);
ReportSvcStatus(gSvcStatus.dwCurrentState, NO_ERROR, 0);
return;
case SERVICE_CONTROL_INTERROGATE:
break;
default:
break;
}
};
//
VOID SvcReportEvent(LPTSTR szFunction)
{
HANDLE hEventSource;
LPCTSTR lpszStrings[2];
TCHAR Buffer[80];
hEventSource = RegisterEventSource(NULL, SVCNAME);
if( NULL != hEventSource )
{
StringCchPrintf(Buffer, 80, TEXT("%s failed with %d"), szFunction, GetLastError());
lpszStrings[0] = SVCNAME;
lpszStrings[1] = Buffer;
ReportEvent(hEventSource, // event log handle
EVENTLOG_ERROR_TYPE, // event type
0, // event category
0, // event identifier
NULL, // no security identifier
2, // size of lpszStrings array
0, // no binary data
lpszStrings, // array of strings
NULL); // no binary data
DeregisterEventSource(hEventSource);
}
};
VOID CALLBACK MainThread(HWND /*hwnd*/,UINT /*uMsg*/,UINT_PTR /*idEvent*/,DWORD /*dwTime*/)
{
myApp();
while( m_bRun )
{
Sleep(1000);
}
};
#include <vector>
/*
**将字符串按指定标识分段
*/
bool string_divide( std::vector<std::string> &_strlist,const std::string src,const std::string div="=")
{
std::string _src = src;
std::string::size_type _pos = _src.find(div);
while(std::string::npos != _pos)
{
std::string _buf = "";
_buf = _src.substr(0,_pos);
_strlist.push_back(_buf);
_src = _src.erase(0,_pos+div.size());
_pos = _src.find(div.c_str());
}
if(!_src.empty()){
_strlist.push_back(_src);
}
return true;
};
//读取文件每一行得字符串并装在到容器中
bool readConfInfo(std::vector<std::string> &list,const std::string path="conf.ini")
{
FILE *m_fil;
if(0==::fopen_s(&m_fil,path.c_str(),"r")){
char buf[512] ={0};
while(NULL!=::fgets(buf,512,m_fil))
{
std::string _lineInfo = buf;
list.push_back(_lineInfo);
}
::fclose(m_fil);
if(list.empty()){
return false;
}
}else{
printf_s("con't open %s \n",path.c_str());
delete m_fil;
return false;
}
return true;
};
bool writeToFile(const char *ptr,const std::string& path="conf.ini", const std::string& mode="w")
{
FILE *m_fil=NULL;
if(0==::fopen_s(&m_fil,path.c_str(),mode.c_str())){
size_t size = 0;
size = ::fwrite(ptr,(int)sizeof(char), strlen(ptr),m_fil);
::fclose(m_fil);
if(size>0){
return true;
}else{
return false;
}
}else{
delete m_fil;
return false;
}
};
void getConf()
{
std::vector<std::string> list;
if(readConfInfo(list)){
for(unsigned int i=0; i<list.size(); i++)
{
std::vector<std::string> _strlist;
string_divide(_strlist,list[i]);
if(2==_strlist.size()){
if(0==strcmp("interval",_strlist[0].c_str())){
G_VALUE::timeL = atoi(_strlist[1].c_str());
if(G_VALUE::timeL<3600){
G_VALUE::timeL=3600;
}
}
if(0==strcmp("cmdtype",_strlist[0].c_str())){
G_VALUE::cmdType = atoi(_strlist[1].c_str());
if(G_VALUE::cmdType<1||G_VALUE::cmdType>3){
G_VALUE::cmdType = 3;
}
}
}
}
}else{
char buf[256]={0};
sprintf_s(buf,"#设置时间间隔(s)\ninterval=%d\n#设置命令类型[1)屏保2)睡眠3)锁屏]\ncmdtype=%d",G_VALUE::timeL,G_VALUE::cmdType);
writeToFile(buf);
}
};
注:屏保程序就不上传了,大家就在自己电脑C:\Windows\System32下查找