Answer the question
In order to leave comments, you need to log in
How to implement system time change in Windows Service in C#?
Good afternoon!
Faced a problem when writing a service for Windows. The service must reset the system time to its original value.
There is a code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Timers;
using System.Runtime.InteropServices;
namespace WindowsService1
{
static class Program
{
[StructLayout(LayoutKind.Sequential)]
private struct SYSTEMTIME //описываем переменную
{
public ushort wYear;
public ushort wMonth;
public ushort wDayOfWeek;
public ushort wDay;
public ushort wHour;
public ushort wMinute;
public ushort wSecond;
public ushort wMilliseconds;
}
[DllImport("kernel32.dll", EntryPoint = "GetSystemTime", SetLastError = true)]
private extern static void Win32GetSystemTime(ref SYSTEMTIME lpSystemTime); //импортируем kernel32.dll и создаем переменную запроса времени из системы
[DllImport("kernel32.dll", EntryPoint = "SetSystemTime", SetLastError = true)]
private extern static bool Win32SetSystemTime(ref SYSTEMTIME lpSystemTime); //импортируем kernel32.dll и создаем переменную запроса на запись времени на систему
private static System.Timers.Timer TimeCycle; //создаем таймер
static void Main()
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new TimeCycleService()
};
ServiceBase.Run(ServicesToRun);
}
private static void Cycle()
{
TimeCycle = new Timer(); //создаем таймер
TimeCycle.Interval = 180000; //время таймера 3 минуты
TimeCycle.Enabled = true; //включаем таймер
TimeCycle.Elapsed += Time; //по окончанию взываем событие
TimeCycle.AutoReset = true; //указываем авторестарт для таймера
}
private static void Time(Object source, ElapsedEventArgs e)
{
SYSTEMTIME time = new SYSTEMTIME(); //создаем переменную
Win32GetSystemTime(ref time); //получаем системное время
time.wMinute = (ushort)(time.wMinute -3); //от существующего времени отнимаем 3 минуты
Win32SetSystemTime(ref time); //записываем время в систему
}
}
}
Answer the question
In order to leave comments, you need to log in
And if you change from the application, it turns out? Here , for some reason, other functions are used.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question