在WIN2000下用VC编程,想设置系统时间。我用了如下程序,没成功,为什么?
SYSTEMTIME systime;
BOOL brtmp;
int ret = 0;
OSVERSIONINFO osv; //定义一个操作系统信息的结构体
systime.wYear=(WORD)m_Year;
systime.wMonth=(WORD)m_Month;
systime.wDay=(WORD)m_Day;
systime.wHour=(WORD)m_Hour;
systime.wMinute=(WORD)m_Minute;
systime.wSecond=(WORD)m_Second;
osv.dwOSVersionInfoSize = sizeof OSVERSIONINFO;
GetVersionEx(&osv); //查询当前操作系统
if(osv.dwPlatformId==VER_PLATFORM_WIN32_NT) //判断是否是2000/NT
{
//下面为向操作系统获取权限操作
HANDLE hProcess,hToken;
TOKEN_PRIVILEGES Privileges;
LUID luid;
hProcess=GetCurrentProcess();
//下面为打开当前进程对话
OpenProcessToken(hProcess,TOKEN_ADJUST_PRIVILEGES,&hToken);
Privileges.PrivilegeCount=1;
LookupPrivilegeValue(NULL,SE_SYSTEMTIME_NAME,&luid);
Privileges.Privileges[0].Luid=luid;
Privileges.Privileges[0].Attributes=SE_PRIVILEGE_ENABLED;
AdjustTokenPrivileges(hToken,FALSE,&Privileges,NULL,NULL,NULL);
}
brtmp=FALSE;
brtmp=SetSystemTime((&systime));
if(brtmp==0)
{
AfxMessageBox("set error");
return ;
}
else
;
每次执行,它总是弹出报错的对话框,显示“set error”。
Ensure if the AdjustTokenPrivileges is passed???
同意楼上的
最好在brtmp=SetSystemTime((&systime));
后调用::GetLastError看一看怎么回事
are you login use administrator??
CTime time = CTime::GetCurrentTime();
不知道CTime类里有没有SetTime 的方法?!
SYSTEMTIME tm;memset(&tm, 0, sizeof(SYSTEMTIME));
sscanf(TimeStr, "%d-%d-%d %d:%d:%d", &tm.wYear, &tm.wMonth, &tm.wDay, &tm.wHour, &tm.wMinute, &tm.wSecond);
if (!SetLocalTime(&tm))
{
//Error Function
}
运行这段代码,win2000下没问题
按照微软的文档,SetLocalTime()或SetSystemTime()要连续调用两次;
试试我下面这段代码:
// enable system-time privilege, set time, disable privilege
if (OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
{
if (LookupPrivilegeValue(NULL, "SeSystemtimePrivilege", &luid))
{
tp.PrivilegeCount = 1;
tp.Privileges[0].Luid = luid;
tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
if (AdjustTokenPrivileges(hToken, FALSE, &tp, sizeof(TOKEN_PRIVILEGES), NULL, NULL))
{
SetLocalTime(&m_packet.systime);
SetLocalTime(&m_packet.systime);
AdjustTokenPrivileges(hToken, TRUE, &tp, sizeof(TOKEN_PRIVILEGES), NULL, NULL);
}
else
{
//错误处理
..........
}
}
CloseHandle(hToken);
}
else
{
//错误处理
..........
}