由于没有时间,就写一个比较简易的定时器程序
// TimerTest.cpp : 定义控制台应用程序的入口点。
#include "stdafx.h"
#include
#include
using namespace std;
#define FAIL_IN_CREATE_TIMER 1
#define FAIL_IN_SET_TIMER 2
#define FAIL_IN_WAITFORSINGLEOBJECT 3
bool WinExit(int iKindOfOperate)
{
HANDLE hToken;
TOKEN_PRIVILEGES tkp;
printf("输入系统操作类型(1.重启 2.关机 3.注销 4.休眠 5.待机):/n");
cin>> iKindOfOperate;
//NT/xp/2000系统在进行系统操作前要先获得权限
if(!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
{
return false;
}
LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &tkp.Privileges[0].Luid);
tkp.PrivilegeCount = 1;
tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
AdjustTokenPrivileges(hToken, FALSE, &tkp, 0, (PTOKEN_PRIVILEGES)NULL, 0);
if(GetLastError() != ERROR_SUCCESS)
{
return false;
}
switch(iKindOfOperate)
{
case 1://重启
ExitWindowsEx(EWX_FORCE|EWX_REBOOT,0);
break;
case 2://关机
ExitWindowsEx(EWX_FORCE|EWX_SHUTDOWN|EWX_POWEROFF,0);
break;
case 3://注销
ExitWindowsEx(EWX_FORCE|EWX_LOGOFF,0);
break;
case 4://休眠
SetSystemPowerState(false,true);
break;
case 5://待机
SetSystemPowerState(true,true);
break;
default: break;
}
return true;
}
//////////////////////////////////////////////////////////////////////////
//Function:CreateTimerTest
//Description:创建定时器
//Input:
// lTimeInterval:定时时间(S)
//Output:
// 无
//Return:
// ERROR_SUCCESS:成功创建
//Others:
//////////////////////////////////////////////////////////////////////////
DWORD CreateTimerTest(long lTimeInterval)
{
HANDLE hTimer = NULL;
BOOL bRet = true;
LARGE_INTEGER liIntervalTime;
liIntervalTime.QuadPart = -lTimeInterval * 10000000;
hTimer = CreateWaitableTimer(NULL, true, L"Close Windows System");
if(!hTimer)
{
printf("Fail in Create Waitable Timer/n");
return FAIL_IN_CREATE_TIMER;
}
bRet = SetWaitableTimer(hTimer, &liIntervalTime, 0, NULL, NULL, 0);
if(!bRet)
{
CloseHandle(hTimer);
return FAIL_IN_SET_TIMER;
}
if (WaitForSingleObject(hTimer, INFINITE) != WAIT_OBJECT_0)
{
printf("Fail in WaitForSingleObject");
return FAIL_IN_WAITFORSINGLEOBJECT;
}
printf("%ld", lTimeInterval);
printf("S定时结束/n");
WinExit(1);
CloseHandle(hTimer);
return ERROR_SUCCESS;
}
//////////////////////////////////////////////////////////////////////////
//
//
//////////////////////////////////////////////////////////////////////////
int _tmain(int argc, _TCHAR* argv[])
{
long lTimeInterval = 0;
setlocale(LC_ALL, "chs");
wstring wsStr = L"请输入定时时间(s): ";
printf("%ws", wsStr.c_str());
cin>>lTimeInterval;
for(;;)
{
//调用定时器
CreateTimerTest(lTimeInterval);
}
return 0;
}