進程守護


 

 

下載地址:

鏈接:https://pan.baidu.com/s/1xbLyWmst29lIN9ss43PlpA
提取碼:0dlf 

 

使用方法:
將要守護的.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; }
}

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM