R
R
RedTea2014-11-27 12:29:38
API
RedTea, 2014-11-27 12:29:38

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);               //записываем время в систему
        }
    }
}

When the server starts, the time does not change, somewhere I made a mistake or did not take into account the features of building the code for the service. Why exactly - I couldn’t find it myself, the service is started on behalf of LocalService and autostart, no one can tell where the mistake was made?
Thank you for your attention!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
asdz, 2014-11-27
@asdz

And if you change from the application, it turns out? Here , for some reason, other functions are used.

R
RedTea, 2014-11-27
@RedTea

I found an error - I didn't format the code correctly.
The code itself needs to be written into the service form with the registration of events, start / stop / restart, etc.
At me the initializing service has been written down in the code.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question