
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Windows;using System.Windows.Controls;using System.Windows.Data;using System.Windows.Documents;using System.Windows.Input;using System.Windows.Media;using System.Windows.Media.Imaging;using System.Windows.Navigation;using System.Windows.Shapes;using System.Windows.Threading;using System.Runtime.InteropServices;using System.Diagnostics;using System.IO;namespace 定时自动关机{  /// <summary>  /// Window1.xaml 的交互逻辑  /// </summary>  public partial class Window1 : Window  {    public Window1()    {      InitializeComponent();    }    [DllImport("user32")]    public static extern int ExitWindowsEx(int x, int y);    private DispatcherTimer Timer1 = new DispatcherTimer();    private int second = 30;    private void Grid_Loaded(object sender, RoutedEventArgs e)    {      AutoRun();      ShutDown();    }    private void Timer1_Tick(object sender, EventArgs e)    {      second--;      this.label2.Content = second.ToString()  "秒";      if (second==0)      {        ExitWindowsEx(1,0);      }    }    private void btnStop_Click(object sender, RoutedEventArgs e)    {      if (Timer1.IsEnabled == true)      {        btnStop.Content = "开始";        Timer1.Stop();      }      else      {        btnStop.Content = "停止";        Timer1.IsEnabled = true;      }    }    private void btnAbort_Click(object sender, RoutedEventArgs e)    {      this.Close();    }    //自启动    public void AutoRun()    {      string StartupPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Startup);      string strEXEpath = Process.GetCurrentProcess().MainModule.FileName;      string strFilepath = Environment.CurrentDirectory;      int l=strEXEpath.LastIndexOf("\\");      string strEXEName = strEXEpath.Substring(l 1);      System.IO.File.Copy(strEXEpath, StartupPath  strEXEName, true);      //获得文件的当前路径      string dir = Directory.GetCurrentDirectory();      //获取可执行文件的全部路径      string exeDir = dir  "自动关机任务.exe";      //获取Run键      Microsoft.Win32.RegistryKey key1 = Microsoft.Win32.Registry.LocalMachine;      Microsoft.Win32.RegistryKey key2 = key1.CreateSubKey("SOFTWARE");      Microsoft.Win32.RegistryKey key3 = key2.CreateSubKey("Microsoft");      Microsoft.Win32.RegistryKey key4 = key3.CreateSubKey("Windows");      Microsoft.Win32.RegistryKey key5 = key4.CreateSubKey("CurrentVersion");      Microsoft.Win32.RegistryKey key6 = key5.CreateSubKey("Run");      //在Run键中写入一个新的键值      key6.SetValue("自动关机", exeDir);      key6.Close();      //如果要取消的话就将key6.SetValue("myForm",exeDir);改成      //key6.SetValue("myForm",false);    }        //进入倒计时关机    public void ShutDown()    {      Timer1.Interval = TimeSpan.FromSeconds(1.0);      Timer1.IsEnabled = true;      Timer1.Tick = new EventHandler(Timer1_Tick);      Timer1.Start();    }   }}

 
  
					
				
评论