计算机使用护眼程序

简介: 开发自己的windows服务app,包含安装、卸载等功能。

这几天爱人老是迷在游戏上,一坐电脑前就是几个小时,还怪我没提醒她休息下,委屈有口难辩,趁她休息时间,给她电脑上个提醒小程序。

思路很简单,做一个小服务,随开机运行,然后设定时间间隔,到点就来个屏保或锁屏啥的,生成的服务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下查找

目录
相关文章
|
3月前
|
存储 编解码 内存技术
A-B罗克韦尔 6180P-15BPXPDC 显示计算机
A-B罗克韦尔 6180P-15BPXPDC 显示计算机
A-B罗克韦尔 6180P-15BPXPDC 显示计算机
|
4月前
|
存储 监控 调度
揭秘计算机奇迹:探索I/O设备的神秘世界!
探索计算机系统中输入输出设备的奥秘!从I/O接口的功能到CPU控制方式,了解不同设备的工作原理和优化方法。深入了解通信方式,提升计算机性能。解锁计算机世界的神秘面纱!
揭秘计算机奇迹:探索I/O设备的神秘世界!
|
4月前
|
调度
计算机操作系统-第十六天
计算机操作系统-第十六天
|
8月前
|
Ubuntu 安全 机器人
将你的计算机变身为果园守护者:与本地树莓派建立连结的乐趣探索!!
将你的计算机变身为果园守护者:与本地树莓派建立连结的乐趣探索!!
55 0
|
存储 Unix 编译器
深入理解计算机系统-第1章计算机系统漫游笔记
计算机系统是由硬件和系统软件组成,它们共同工作来运行应用程序。C 语言是系统级编程的首选,同时它也非常实用于应用级程序的编写。
102 0
|
存储 Unix Linux
限免下载!揭秘你不知道的计算机“进化论”
一书读懂计算机发展百年历史!带你趣味体会那些你不曾知道的“秘密”,了解计算机的发展起源。
23650 0
限免下载!揭秘你不知道的计算机“进化论”
|
测试技术
想写程序吗?远离你的计算机!
导读:原文来自blog.rtwilson.com上一篇博客《Want to write some code? Get away from your computer!》。译文由外刊IT整理编译《想写程序吗?远离你的计算机!》。
797 0