进程守护

  • A+
所属分类:.NET技术
摘要

  链接:https://pan.baidu.com/s/1FYCtn9bNoekRp58tIJr9Lg
提取码:a1l2  使用方法:
将要守护的.exe文件拖入即可

进程守护

 

 

下载地址:

链接:https://pan.baidu.com/s/1FYCtn9bNoekRp58tIJr9Lg
提取码:a1l2 

 

使用方法:
将要守护的.exe文件拖入即可

 

using FY; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Text; using System.Threading; using System.Windows.Forms;  namespace DaemonWF {     public partial class Form1 : Form     {         List<processModel> list = new List<processModel>();         ContextMenuStrip strip = new ContextMenuStrip();          public Form1()         {             InitializeComponent();         }         private void Form1_Load(object sender, EventArgs e)         {             this.listView1.Columns.Add("路径", 400, HorizontalAlignment.Left); //一步添加             this.listView1.Columns.Add("状态", 80, HorizontalAlignment.Left); //一步添加             listView1.View = View.Details;             strip.Click += Items1_Click;              ReadTxt();              //程序处理             Thread thread1 = new Thread(new ThreadStart(Restart));             thread1.Start();         }          private void Form1_FormClosed(object sender, FormClosedEventArgs e)         {             Environment.Exit(0);         }          /// <summary>         /// 程序处理         /// </summary>         public void Restart()         {             while (true)             {                 try                 {                     if (list.Count > 0)                     {                         for (int i = 0; i < list.Count; i++)                         {                             string exeName = list[i].Path.Split('\')[list[i].Path.Split('\').Length - 1].Split('.')[0];                             if (list[i].State == 1)                             {                                 try                                 {                                     if (Process.GetProcessesByName(exeName).Length < 1)                                     {                                         SetText(list[i], 5);                                         Process.Start(list[i].Path);                                     }                                     SetText(list[i], 6);                                      Thread.Sleep(100);                                 }                                 catch (Exception ex)                                 {                                     if (ex.ToString().Contains("系统找不到指定的文件"))                                     {                                         MessageBox.Show("找不到指定的文件:" + list[i].Path + ",请检查路径的准确性", "消息", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);                                         list[i].State = 8;                                         SetText(list[i], 8);                                     }                                     else                                     {                                         MessageBox.Show(ex.ToString(), "消息", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);                                     }                                 }                             }                             if (list[i].State == 3)                             {                                 Process[] processes = Process.GetProcesses();                                 foreach (Process p in processes)                                 {                                     if (p.ProcessName == exeName)                                     {                                         p.Kill();                                     }                                     SetText(list[i], 7);                                 }                                 if (Process.GetProcessesByName(exeName).Length < 1)                                 {                                     SetText(list[i], 7);                                 }                             }                         }                     }                  }                 catch (Exception ex)                 {                     if (ex.ToString().Contains("系统找不到指定的文件"))                     {                         MessageBox.Show("系统找不到指定的文件,请检查路径的准确性", "消息", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);                     }                     else                     {                         MessageBox.Show(ex.ToString(), "消息", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);                     }                 }                 Thread.Sleep(3000);             }         }          private void Form1_DragDrop(object sender, DragEventArgs e)         {              string path = ((System.Array)e.Data.GetData(DataFormats.FileDrop)).GetValue(0).ToString();             if (path.Split('.')[path.Split('.').Length - 1].ToUpper() != "EXE")             {                 MessageBox.Show(path + "不是可执行程序");                 return;             }             for (int i = 0; i < list.Count; i++)             {                 if (list[i].Path == path)                 {                     MessageBox.Show(path + "已存在!");                     return;                 }             }              list.Add(new processModel()             {                 Path = path,                 State = 1             });               this.listView1.BeginUpdate();   //数据更新,UI暂时挂起,直到EndUpdate绘制控件,可以有效避免闪烁并大大提高加载速度               ListViewItem lvi = new ListViewItem();             lvi.Text = path;             lvi.SubItems.Add("正在启动");             this.listView1.Items.Add(lvi);             this.listView1.EndUpdate();  //结束数据处理,UI界面一次性绘制。          }          private void Form1_DragEnter(object sender, DragEventArgs e)         {             if (e.Data.GetDataPresent(DataFormats.FileDrop))                 e.Effect = DragDropEffects.Link;             else e.Effect = DragDropEffects.None;         }          private void listView1_MouseClick(object sender, MouseEventArgs e)         {             if (e.Button == MouseButtons.Right)             {                 if (true)//看看是否过滤当前状态                 {                     string state = listView1.FocusedItem.SubItems[1].Text;                     strip.Items.Clear();                     if (state == "启动成功" || state == "正在启动" || state == "开始监控")                     {                         strip.Items.Add("停止监控");                         strip.Items.Add("关闭进程");                         strip.Items.Add("删除监控");                     }                     else if (state == "停止监控")                     {                         strip.Items.Add("开始监控");                         strip.Items.Add("关闭进程");                         strip.Items.Add("删除监控");                     }                     else if (state == "正在关闭" || state == "关闭成功")                     {                         strip.Items.Add("开始监控");                         strip.Items.Add("删除监控");                     }                     else if (state == "启动失败")                     {                         strip.Items.Add("开始监控");                         strip.Items.Add("删除监控");                     }                 }                 strip.Show(listView1, e.Location);//鼠标右键按下弹出菜单             }         }          private void Items1_Click(object sender, EventArgs e)         {             foreach (ToolStripItem items in strip.Items)             {                 if (items.Selected == true)                 {                     switch (items.Text)                     {                         case "开始监控": listView1Select(1); break;                         case "停止监控": listView1Select(2); break;                         case "关闭进程": listView1Select(3); break;                         case "删除监控": listView1Select(4); break;                          default:                             break;                     }                 }              }         }          public void listView1Select(int op)         {             string path = listView1.FocusedItem.SubItems[0].Text;             listView1.FocusedItem.SubItems[1].Text = GetState(op);             for (int i = 0; i < list.Count; i++)             {                 if (list[i].Path == path)                 {                     if (op == 4)                     {                         listView1.Items.Remove(listView1.FocusedItem);                         list.Remove(list[i]);                     }                     else                     {                         list[i].State = op;                         if (op == 1)                         {                             listView1.FocusedItem.SubItems[1].Text = GetState(5);                         }                     }                  }             }         }          public string GetState(int op)         {             switch (op)             {                 case 1: return "开始监控";                 case 2: return "停止监控";                 case 3: return "正在关闭";                 case 4: return "删除监控";                 case 5: return "正在启动";                 case 6: return "启动成功";                 case 7: return "关闭成功";                 case 8: return "启动失败";                 default: return "OP码有误";             }         }          public void SetText(processModel model, int op)         {             this.BeginInvoke(new Action(() =>             {                 try                 {                     for (int j = 0; j < listView1.Items.Count; j++)                     {                         if (listView1.Items[j].SubItems[0].Text == model.Path)                         {                             listView1.Items[j].SubItems[1].Text = GetState(op);                         }                     }                 }                 catch (Exception ex)                 {                     RBILogs.WriteLog("error", ex.ToString());                 }              }));         }          /// <summary>         /// 读取历史监控记录         /// </summary>         public void ReadTxt()         {             string path = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "Logs\" + "FY.txt";             StreamReader sr = new StreamReader(path, Encoding.Default);             string line;             while ((line = sr.ReadLine()) != null)             {                 if (!string.IsNullOrEmpty(line))                 {                     list.Add(new processModel()                     {                         Path = line,                         State = 1                     });                     this.listView1.BeginUpdate();   //数据更新,UI暂时挂起,直到EndUpdate绘制控件,可以有效避免闪烁并大大提高加载速度                       ListViewItem lvi = new ListViewItem();                     lvi.Text = line;                     lvi.SubItems.Add("正在启动");                     this.listView1.Items.Add(lvi);                     this.listView1.EndUpdate();  //结束数据处理,UI界面一次性绘制。                   }             }             sr.Close();         }          /// <summary>         /// 关闭程序记录监控程序路径         /// </summary>         public void WriteFY()         {             string path = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "Logs\" + "FY.txt";             FileStream fs = new FileStream(path, FileMode.Truncate, FileAccess.ReadWrite);             fs.Close();             for (int i = 0; i < list.Count; i++)             {                 RBILogs.WriteLog2(list[i].Path);             }         }          /// <summary>         /// 添加双击托盘图标事件(双击显示窗口)         /// </summary>         /// <param name="sender"></param>         /// <param name="e"></param>         private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)         {             if (WindowState == FormWindowState.Minimized)             {                 //还原窗体显示                     WindowState = FormWindowState.Normal;                 //激活窗体并给予它焦点                 this.Activate();                 //任务栏区显示图标                 this.ShowInTaskbar = true;                 //托盘区图标隐藏                 notifyIcon1.Visible = false;             }         }          /// <summary>         /// 判断是否最小化,然后显示托盘         /// </summary>         /// <param name="sender"></param>         /// <param name="e"></param>         private void Form1_SizeChanged(object sender, EventArgs e)         {             //判断是否选择的是最小化按钮             if (WindowState == FormWindowState.Minimized)             {                 //隐藏任务栏区图标                 this.ShowInTaskbar = false;                 //图标显示在托盘区                 notifyIcon1.Visible = true;             }         }          /// <summary>         /// 确认是否退出         /// </summary>         /// <param name="sender"></param>         /// <param name="e"></param>         private void Form1_FormClosing(object sender, FormClosingEventArgs e)         {             if (MessageBox.Show("是否确认退出程序?", "退出", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)             {                 WriteFY();                 // 关闭所有的线程                 this.Dispose();                 this.Close();                 Environment.Exit(0);             }             else             {                 e.Cancel = true;             }         }          /// <summary>         /// 托盘右键显示主界面         /// </summary>         /// <param name="sender"></param>         /// <param name="e"></param>         private void 显示ToolStripMenuItem_Click(object sender, EventArgs e)         {             WindowState = FormWindowState.Normal;         }          /// <summary>         /// 托盘右键退出程序         /// </summary>         /// <param name="sender"></param>         /// <param name="e"></param>         private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)         {             if (MessageBox.Show("是否确认退出程序?", "退出", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)             {                 WriteFY();                 // 关闭所有的线程                 this.Dispose();                 this.Close();                 Environment.Exit(0);             }         }     } }   /// <summary> /// 进程处理Model /// </summary> public class processModel {     public string Path { get; set; }     //  1开始监控 2停止监控 3关闭进程  4删除监控 5正在启动  6启动成功 7关闭成功     public int State { get; set; } }