#define UNICODE 1
#define _UNICODE 1
#include <windows.h>
#include <stdio.h>
#include <string.h>
typedef struct _REG_TZI_FORMAT
{
LONG Bias;
LONG StandardBias;
LONG DaylightBias;
SYSTEMTIME StandardDate;
SYSTEMTIME DaylightDate;
} REG_TZI_FORMAT;
BOOL SetTimeZone(wchar_t * subkey)
{
// XP下需要获取权限 SE_TIME_ZONE_NAME
HANDLE hToken;
TOKEN_PRIVILEGES tkp;
OpenProcessToken(GetCurrentProcess(),
TOKEN_ADJUST_PRIVILEGES|TOKEN_QUERY, &hToken);
LookupPrivilegeValue(
NULL, TEXT("SeTimeZonePrivilege"), &tkp.Privileges[0].Luid);
tkp.PrivilegeCount = 1;
tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
AdjustTokenPrivileges(hToken, FALSE, &tkp, 0, (PTOKEN_PRIVILEGES)NULL, 0);
//查询注册表获取对应时区, 时区数据结构
HKEY hKey;
TIME_ZONE_INFORMATION tziNew;
REG_TZI_FORMAT regTZI;
DWORD dwBufLen=sizeof(regTZI);
LONG lRet;
wchar_t lpSubKey[MAX_PATH]=L"Software\\Microsoft\\Windows NT\\CurrentVersion\\Time Zones\\";
wcscat(lpSubKey,subkey);
lRet = RegOpenKeyEx(HKEY_LOCAL_MACHINE,lpSubKey ,0, KEY_QUERY_VALUE, &hKey );
if( lRet != ERROR_SUCCESS )
{
printf("打开注册表失败!\n");
return FALSE;
}
lRet = RegQueryValueEx( hKey, TEXT("TZI"), NULL, NULL,(LPBYTE)®TZI, &dwBufLen);
RegCloseKey(hKey);
if( (lRet != ERROR_SUCCESS) || (dwBufLen > sizeof(regTZI)) )
{
printf("查询注册表失败!\n");
return FALSE;
}
// 设置时区
ZeroMemory(&tziNew, sizeof(tziNew));
tziNew.Bias = regTZI.Bias;
tziNew.StandardDate = regTZI.StandardDate;
wcscpy(tziNew.StandardName, L"");
wcscpy(tziNew.DaylightName, L"");
tziNew.DaylightDate = regTZI.DaylightDate;
tziNew.DaylightBias = regTZI.DaylightBias;
if( !SetTimeZoneInformation( &tziNew ) )
{
printf("Failure1: %d\n", GetLastError());
return FALSE;
}
// 释放权限令牌
tkp.Privileges[0].Attributes = 0;
AdjustTokenPrivileges(hToken, FALSE, &tkp, 0, (PTOKEN_PRIVILEGES) NULL, 0);
return TRUE;
}
wchar_t * chartowchar(char * str)
{
int len=MultiByteToWideChar(CP_ACP,0,str, -1, NULL,0);
wchar_t *w_string = new wchar_t[len];
memset(w_string,0,sizeof(wchar_t)*len);
MultiByteToWideChar(CP_ACP, 0, str,-1,w_string, len);
return w_string;
}
int main(int argc,char *argv[])
{
char * c=argv[1];
BOOL a=SetTimeZone(chartowchar(c));
}
由于TIME_ZONE_INFORMATION结构没有TimeZoneKeyName ,以上代码在win7环境下会有BUG,应改为使用
BOOL WINAPI SetDynamicTimeZoneInformation(
_In_ const DYNAMIC_TIME_ZONE_INFORMATION *lpTimeZoneInformation
);
typedef struct _TIME_DYNAMIC_ZONE_INFORMATION { LONG Bias; WCHAR StandardName[32]; SYSTEMTIME StandardDate; LONG StandardBias; WCHAR DaylightName[32]; SYSTEMTIME DaylightDate; LONG DaylightBias; WCHAR TimeZoneKeyName[128]; BOOLEAN DynamicDaylightTimeDisabled; } DYNAMIC_TIME_ZONE_INFORMATION, *PDYNAMIC_TIME_ZONE_INFORMATION;