解决电脑自动开机问题

来源:互联网 发布:下列属于软件特性 编辑:程序博客网 时间:2024/04/28 08:44

最近一段时间笔记本电脑老是自动开机,拿去修也没修好,果断写个程序让电脑自动休眠

using System;using System.Diagnostics;using System.IO;using System.ServiceProcess;using System.Timers;namespace WindowsService1{    public partial class Service1 : ServiceBase    {        public static string FILENAME = "C://Myservice.log";        public static DateTime lastTimePoint;        //dosCommand Dos命令语句        public static string Execute(string dosCommand)        {            return Execute(dosCommand, 10);        }        // 执行DOS命令,返回DOS命令的输出        public static string Execute(string command, int seconds)        {            string output = ""; //输出字符串            if (command != null && !command.Equals(""))            {                Process process = new Process();//创建进程对象                ProcessStartInfo startInfo = new ProcessStartInfo();                startInfo.FileName = "cmd.exe";//设定需要执行的命令                startInfo.Arguments = "/C " + command;//“\C”表示执行完命令后马上退出                startInfo.UseShellExecute = false;//不使用系统外壳程序启动                startInfo.RedirectStandardInput = false;//不重定向输入                startInfo.RedirectStandardOutput = true; //重定向输出                startInfo.CreateNoWindow = true;//不创建窗口                process.StartInfo = startInfo;                try                {                    if (process.Start())//开始进程                    {                        if (seconds == 0)                            process.WaitForExit();//这里无限等待进程结束                        else                            process.WaitForExit(seconds); //等待进程结束,等待时间为指定的毫秒                        output = process.StandardOutput.ReadToEnd();//读取进程的输出                    }                }                catch { }                finally                {                    if (process != null)                        process.Close();                }            }            return output;        }        public Service1()        {            InitializeComponent();        }        //文件写入操作        public static void LogFile(string filename, string buf)        {            try {                FileStream fs = new FileStream(filename, FileMode.Append);                byte[] data = System.Text.Encoding.Default.GetBytes(buf + "\r\n");                fs.Write(data, 0, data.Length);                fs.Flush();                fs.Close();            }            catch (Exception e)            {                Console.WriteLine("cannot open file");            }        }        private static void onTimeEvent(object source, ElapsedEventArgs e)        {            DateTime now = DateTime.Now;            if (now > lastTimePoint.AddMinutes(5))            //时间相差超过5分钟,可以认为是电脑重新启动            {                LogFile(FILENAME, "[!] 检测到电脑启动: " + now );                lastTimePoint = now;                setAutoCheck();                return;            }            lastTimePoint = now;        }        public static void setAutoCheck()        {            System.Timers.Timer t = new System.Timers.Timer(5 * 60 * 1000);            //正常状态下,用户会在五分钟内进行登录操作,所以登录检查设定在五分钟以后            t.Elapsed += new System.Timers.ElapsedEventHandler(loginCheck);            t.AutoReset = false;            t.Enabled = true;            t.Start();        }       /*         public static void _startClient()        {            FileStream f = File.Open(@"D:\setting.txt", FileMode.Open);            byte[] buff = new byte[1024];            f.Read(buff, 0, buff.Length);            f.Close();            string path = System.Text.Encoding.ASCII.GetString(buff);            LogFile(FILENAME, path);            Process process = new Process();//创建进程对象            ProcessStartInfo startInfo = new ProcessStartInfo();            startInfo.FileName = path;//设定需要执行的命令            startInfo.UseShellExecute = false;//不使用系统外壳程序启动            startInfo.RedirectStandardInput = false;//不重定向输入            startInfo.RedirectStandardOutput = true; //重定向输出            startInfo.CreateNoWindow = false;//不创建窗口            process.Start();            process.WaitForExit();        }        public static void startClient()        {            Thread t = new Thread(_startClient);            t.Start();        }        */        private static void loginCheck(object source, System.Timers.ElapsedEventArgs e)        {            if (DateTime.Now > lastTimePoint.AddMinutes(5))            {                String time = DateTime.Now.ToString();                LogFile(FILENAME, "[!] 当前时间: " + time );                LogFile(FILENAME, "[!] 计时器超时,自动失效");                return;            }            if(! isLogin())            {                /*                Process[] proc = Process.GetProcessesByName("AutoShutdownClient");                if (proc.Length == 0)                {                    LogFile(FILENAME, "客户端进程未打开");                }                else                {                    TcpClient tc = new TcpClient();                    tc.Connect(IPAddress.Parse("127.0.0.1"), 6789);                    NetworkStream ns = tc.GetStream();                    StreamReader sr = new StreamReader(ns);                    sr.ReadLine();                    string tmp = "shutdown?\r\n";                    ns.Write(System.Text.Encoding.ASCII.GetBytes(tmp), 0, tmp.Length);                    string result = sr.ReadLine();                    if (result.Contains("no"))                    {                        return;                    }                }                */                String time = DateTime.Now.ToString();                LogFile(FILENAME, "[!] 当前时间: "+time);                LogFile(FILENAME, "[!] 非正常启动,将立即尝试自动休眠电脑");                LogFile(FILENAME, Execute("shutdown /h"));            }        }        public static bool isLogin()        {            string logType1 = "Security";            EventLog e = new EventLog(logType1);            int length = e.Entries.Count;            DateTime now = DateTime.Now;            for (int i = length - 1; ; i--)            {                EventLogEntry l = e.Entries[i];                if (l.TimeGenerated > now.AddMinutes(-10))                //过滤掉十分钟以前的事件                {                    if (l.InstanceId == 4624 && l.Message.Contains("bluekezhou@qq.com"))                    {                        //用户登录事件id为4624                        LogFile(FILENAME, "[*] 检测到登录事件:" +                                    l.InstanceId.ToString() + " " +                                    l.TimeGenerated );                        return true;                    }                }                else                    break;            }            LogFile(FILENAME, "[*] 没有检测用户登录");            return false;        }        protected override void OnStart(string[] args)        {            String time = DateTime.Now.ToString();            LogFile(FILENAME, "\r\n" + time);            LogFile(FILENAME, "[*] 服务启动");            lastTimePoint = DateTime.Now;            setAutoCheck();            //设置触发器            System.Timers.Timer aTimer = new System.Timers.Timer();            aTimer.Elapsed += new System.Timers.ElapsedEventHandler(onTimeEvent);            aTimer.AutoReset = true;            //每60秒(一分钟)触发一次检测            aTimer.Interval = 60000;            aTimer.Enabled = true;            aTimer.Start();            LogFile(FILENAME, "[*] 监听器设置完毕");        }        protected override void OnStop()        {            String time = DateTime.Now.ToString();            LogFile(FILENAME, "\r\n" + time);            LogFile(FILENAME, "[*] 服务停止");        }    }}
0 0
原创粉丝点击