using System;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Windows.Forms;
using Microsoft.Win32;
namespace AutoShutdown
{
class Program
{
private static readonly string AppName = "SystemService";
private static readonly string AppPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), $"{AppName}.exe");
private static readonly string RegKey = @"Software\Microsoft\Windows\CurrentVersion\Run";
static void Main(string[] args)
{
using (Mutex mutex = new Mutex(true, AppName, out bool createdNew))
{
if (!createdNew)
{
return;
}
CheckFirstRun();
SetupAutoStart();
RunInBackground();
}
}
static void CheckFirstRun()
{
RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Software\MyApp", true);
if (key == null)
{
key = Registry.CurrentUser.CreateSubKey(@"Software\MyApp");
}
if (key.GetValue("FirstRun") == null || (int)key.GetValue("FirstRun") == 0)
{
MessageBox.Show("此程序将每天在12:05和17:25自动关机,仅用于技术学习。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
key.SetValue("FirstRun", 1);
}
key.Close();
}
static void SetupAutoStart()
{
if (Environment.GetCommandLineArgs()[0] != AppPath)
{
if (!File.Exists(AppPath))
{
File.Copy(Environment.GetCommandLineArgs()[0], AppPath);
}
RegistryKey key = Registry.CurrentUser.OpenSubKey(RegKey, true);
if (key != null && key.GetValue(AppName) == null)
{
key.SetValue(AppName, $"\"{AppPath}\"");
}
key?.Close();
}
}
static void RunInBackground()
{
bool isShuttingDown = false;
while (true)
{
DateTime now = DateTime.Now;
bool nearTargetTime = (now.Hour == 12 && now.Minute == 4 && now.Second >= 30) ||
(now.Hour == 12 && now.Minute == 5 && now.Second <= 30) ||
(now.Hour == 17 && now.Minute == 24 && now.Second >= 30) ||
(now.Hour == 17 && now.Minute == 25 && now.Second <= 30);
if (!isShuttingDown && nearTargetTime)
{
if ((now.Hour == 12 && now.Minute == 5 && now.Second == 0) ||
(now.Hour == 17 && now.Minute == 25 && now.Second == 0))
{
isShuttingDown = true;
Thread.Sleep(500);
Process.Start(new ProcessStartInfo
{
FileName = "cmd.exe",
Arguments = "/c shutdown /s /f /t 0",
CreateNoWindow = true,
UseShellExecute = false
});
break;
}
Thread.Sleep(1000);
}
else
{
Thread.Sleep(30000);
}
}
}
}
}