2009. április 21., kedd

Changing system date and time in Windows


Problem/Question/Abstract:

I want to assign a new time to the system time. How would I do this? I tried to get the system time through GetSystemTime() and set the new time to SetSystemTime(), but I get the wrong results.

Answer:

Solve 1:

This sets the time to the same time in year 1999:

procedure TForm1.Set1999(Sender: TObject);
var
  stSystemTime: TSystemTime;
begin
  Windows.GetLocalTime(stSystemTime);
  stSystemTime.wYear := 1999;
  Windows.SetLocalTime(stSystemTime);
end;


Solve 2:

By using the following call (example is a method of a button click) you may directly modify the date and time of Windows.

procedure TForm1.Button1Click(Sender: TObject);
var
  NewTime: TSystemTime;
begin
  FillChar(NewTime, sizeof(NewTime), #0);
  NewTime.wYear := 2000;
  NewTime.wMonth := 8;
  NewTime.wDay := 28;
  NewTime.wHour := 0;
  NewTime.wMinute := 0;
  NewTime.wSecond := 0;
  NewTime.wMilliseconds := 0;

  SetLocalTime(NewTime);
end;

Please note that when you do chage the system time, send a WM_TIMECHANGE message to all toplevel windows so that they can detect the time change...  You should do this for all version of windows but 2000 since it does it by its self.  Bellow is the code:

if IsWin2000 = False then
  SendMessage(HWND_TOPMOST, WM_TIMECHANGE, 0, 0);

function IsWin2000(): Boolean;
var
  OSInfo: TOSVersionInfo;
begin
  Result := False;
  OSInfo.dwOSVersionInfoSize := SizeOf(OsInfo);
  if not GetVersionEx(OSInfo) then
  begin
    Exit;
  end;
  if OsInfo.dwPlatformID = VER_PLATFORM_WIN32_NT then
  begin
    if OSInfo.dwMajorVersion >= 5 then
      Result := True;
  end;
end;

Nincsenek megjegyzések:

Megjegyzés küldése