winform简单监控进程(关闭后自动启动)

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using System.IO;

namespace ProcessMonitor
{
    public partial class MainForm : Form
    {
        private int interval = 60000;//监控间隔
        DateTime d_start = DateTime.Now;//统计累计监控时长
        public MainForm()
        {
            InitializeComponent();
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            //读取进程列表
            try
            {
                string[] names = ConfigurationManager.AppSettings.Get("processNames").Split(',');//读取config文件要监控的进程
                interval = int.Parse(ConfigurationManager.AppSettings.Get("interval"));//读取监控间隔
                //如果监控进程数量大于0
                if (names.Where(o => !string.IsNullOrEmpty(o)).Count() > 0)
                {
                    timer1.Enabled = true;//启动定时器
                    timer1.Interval = interval;//设置定时间监控间隔
                }
                else
                {
                    MessageBox.Show("请配置要监控的进程");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("请配置要监控的进程");
            }
        }
        /// <summary>
        /// 通过定时器循环监控
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer1_Tick(object sender, EventArgs e)
        {
            dataGridView1.Rows.Clear();//将进程情况显示在表格中
            DataGridViewRow row = new DataGridViewRow();
            string[] names = ConfigurationManager.AppSettings.Get("processNames").Split(',');//读取config文件要监控的进程
            foreach (var name in names)
            {
                row = new DataGridViewRow();
                row.CreateCells(dataGridView1);
                //获取应用程序名称
                string exeName = Path.GetFileName(name).Replace(Path.GetExtension(name), "");
                row.Cells[0].Value = exeName;
                Process pName = Process.GetProcessesByName(exeName).FirstOrDefault();
                //该进程不存在并且该文件存在
                if (pName == null && File.Exists(@name))
                {
                    try
                    {
                        Process.Start(@name);//启动程序
                        System.Threading.Thread.Sleep(500);
                        row.Cells[1].Value = "启动中";
                        row.Cells[2].Value = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    }
                    catch (Exception ex)
                    {
                        row.Cells[1].Value = "启动失败";
                        row.Cells[2].Value = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    }
                }
                else
                {
                    row.Cells[1].Value = "已启动";
                    row.Cells[2].Value = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                }
                dataGridView1.Rows.Add(row);
            }
        }

        private void MainForm_SizeChanged(object sender, EventArgs e)
        {
            // 判断只有最小化时,隐藏窗体
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.Hide();
            }
        }

        private void notifyIcon1_DoubleClick(object sender, EventArgs e)
        {
            // 正常显示窗体
            this.Visible = true;
            this.WindowState = FormWindowState.Normal;
        }

        private void timer2_Tick(object sender, EventArgs e)
        {
            double dd = (DateTime.Now - d_start).TotalDays;
            lbl_time.Text = DateDiffByTime(dd);
        }

        /// <summary>
        /// 时间转换
        /// </summary>
        /// <param name="ts"></param>
        /// <returns></returns>
        private string DateDiffByTime(double ts)
        {
            int days = (int)ts;//天
            int hours = (int)((ts - days) * 24);
            int minutes = (int)((((ts - days) * 24) - hours) * 60);
            int second = (int)((((((ts - days) * 24) - hours) * 60) - minutes) * 60);
            return days + "天" + hours + "小时" + minutes + "分" + second + "秒";
        }
    }
}


  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
WinForm实现彻底关闭后等待2秒自动启动可以通过以下步骤来实现: 1. 创建一个Windows应用程序。 2. 在应用程序的FormClosing事件中,判断窗口是否是被用户手动关闭,如果是,则使用`System.Diagnostics.Process.Start(Application.ExecutablePath)`方法重新启动应用程序并退出当前进程。 3. 在应用程序的Main函数中,判断当前应用程序是否正在运行,如果正在运行,则等待2秒钟后重新启动应用程序。 示例代码如下: ```csharp static bool isRunning = false; static void Main() { // 判断当前应用程序是否正在运行 Mutex mutex = new Mutex(true, "MyApp", out isRunning); if (!isRunning) { // 等待2秒钟后重新启动应用程序 System.Threading.Thread.Sleep(2000); System.Diagnostics.Process.Start(Application.ExecutablePath); return; } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new MainForm()); } private void MainForm_FormClosing(object sender, FormClosingEventArgs e) { // 判断窗口是否是被用户手动关闭 if (e.CloseReason == CloseReason.UserClosing) { // 使用System.Diagnostics.Process.Start(Application.ExecutablePath)方法重新启动应用程序 System.Diagnostics.Process.Start(Application.ExecutablePath); // 退出当前进程 System.Diagnostics.Process.GetCurrentProcess().Kill(); } } ``` 需要注意的是,在使用`System.Diagnostics.Process.Start(Application.ExecutablePath)`方法重新启动应用程序时,需要确保应用程序的可执行文件位于正确的路径下,并且在重新启动之前,需要确保所有的数据已经保存。同时,也需要注意在关闭窗口时,要确保在窗口关闭时释放所有资源。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值