using System; using System.ServiceProcess; using System.Diagnostics; using System.Timers; using System.Xml; using System.Management; public class PWatch : ServiceBase { protected ManagementObjectSearcher objS; protected ObjectQuery objQ; protected Timer timer; protected XmlDocument xmldoc; protected XmlNodeList watchList; protected string smtpServer; protected string smtpFrom; protected string smtpTo; protected string smtpSubject; protected string smtpBody; public static void Main() { ServiceBase.Run(new PWatch()); } public PWatch() { CanPauseAndContinue = true; ServiceName = "ProcessWatch"; objQ = new ObjectQuery(); objS = new ManagementObjectSearcher(objQ); xmldoc = new XmlDocument(); timer = new Timer(); } protected void SmtpMail(string name) { System.Web.Mail.SmtpMail.SmtpServer = smtpServer; System.Web.Mail.SmtpMail.Send( smtpFrom, smtpTo, smtpSubject, name + " " + smtpBody); } protected void ChkProcess(string name) { Boolean flg = false; objQ.QueryString = "Select Name from Win32_Process where Name='" + name + "'"; objS.Query = objQ; ManagementObjectCollection moc = objS.Get(); if( moc.Count != 0 ) { flg = true; } moc.Dispose(); moc = null; if( flg == false ) { EventLog.WriteEntry("ChkProcess Error: " + name); SmtpMail(name); } GC.Collect(); } protected override void OnStart(string[] args) { EventLog.WriteEntry("ProcesWatch Service started"); xmldoc.Load("pwatch.xml"); XmlElement root = xmldoc.DocumentElement; XmlNodeList list = root.GetElementsByTagName("watch_interval"); timer.Interval = Convert.ToInt32(list[0].FirstChild.Value); list = root.GetElementsByTagName("smtpserver"); smtpServer = list[0].FirstChild.Value; list = root.GetElementsByTagName("from"); smtpFrom = list[0].FirstChild.Value; list = root.GetElementsByTagName("to"); smtpTo = list[0].FirstChild.Value; list = root.GetElementsByTagName("subject"); smtpSubject = list[0].FirstChild.Value; list = root.GetElementsByTagName("body"); smtpBody = list[0].FirstChild.Value; watchList = root.GetElementsByTagName("watch"); timer.Elapsed += new ElapsedEventHandler(OnTimer); timer.Enabled = true; } protected override void OnStop() { EventLog.WriteEntry("ProcessWatch Service stopped"); timer.Enabled = false; } protected override void OnPause() { EventLog.WriteEntry("ProcessWatch Service paused"); timer.Enabled = false; } protected override void OnContinue() { EventLog.WriteEntry("ProcessWatch Service continued"); timer.Enabled = true; } protected void OnTimer(Object source, ElapsedEventArgs e) { for(int i=0; i<watchList.Count; i++) { // EventLog.WriteEntry(watchList[i].FirstChild.Value; ChkProcess(watchList[i].FirstChild.Value); } } }