StableVersion4.3/AutomaticTimingWindowsService/TimingService.cs

110 lines
3.6 KiB
C#

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Security.Principal;
using System.ServiceProcess;
using System.Text;
using System.Windows.Forms;
namespace AutomaticTimingWindowsService
{
partial class TimingService : ServiceBase
{
/// <summary>
/// 日志文件路径
/// </summary>
private string logPath = Application.StartupPath + @"\Log";
/// <summary>
/// 日志文件
/// </summary>
FileClass fileClass = new FileClass();
System.Timers.Timer timer = new System.Timers.Timer(1000);
public TimingService()
{
InitializeComponent();
}
protected void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
timer.Interval = int.Parse(ConfigurationManager.AppSettings["Interval"] + "");
timer.Enabled = false;
//fileClass.WriteLogFile(logPath, "定时器" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"));
DateTime dateTime;
string message;
if (!IsAdministrator())
{
fileClass.WriteLogFile(logPath, "请以管理员身份运行程序!");
return;
}
if (SystemTime.Synchronization(ConfigurationManager.AppSettings["IP"], out dateTime, out message))
{
fileClass.WriteLogFile(logPath, "校时成功!");
}
else
{
fileClass.WriteLogFile(logPath, "请联系管理员!");
}
timer.Enabled = true;
}
protected override void OnStart(string[] args)
{
timer.Interval = int.Parse(ConfigurationManager.AppSettings["Interval"] + "");
if (timer != null)
{
timer.Elapsed += new System.Timers.ElapsedEventHandler(Timer_Elapsed);
timer.Enabled = true;
timer.AutoReset = true;
}
DateTime dateTime;
string message;
if (!IsAdministrator())
{
fileClass.WriteLogFile(logPath, "请以管理员身份运行程序!");
return;
}
if (SystemTime.Synchronization(ConfigurationManager.AppSettings["IP"], out dateTime, out message))
{
fileClass.WriteLogFile(logPath, "校时成功!");
}
else
{
fileClass.WriteLogFile(logPath, "请联系管理员!");
}
}
protected override void OnStop()
{
if (timer != null)
{
timer.Elapsed -= new System.Timers.ElapsedEventHandler(Timer_Elapsed);
timer.Enabled = false;
}
}
public bool IsAdministrator()
{
WindowsIdentity identity = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(identity);
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.UseShellExecute = true;
startInfo.WorkingDirectory = Environment.CurrentDirectory;
startInfo.FileName = Application.ExecutablePath;
startInfo.Verb = "runas";
try
{
Process.Start(startInfo);
}
catch (Exception e)
{
fileClass.WriteLogFile(logPath, e.Message);
}
return principal.IsInRole(WindowsBuiltInRole.Administrator);
}
}
}