FORM1代码
下面展示代码
using System;
using System.Windows.Forms;
using System.Diagnostics;//引入Process 类
using System.IO;
namespace 监测自启动
{
public partial class Form1 : Form
{
private Process[] MyProcesses=null;//需要监控的程序名,该方法带出该程序所有用到的进程
private string path=System.Windows.Forms.Application.StartupPath;
private string text=null;
private void readconfig()
{
StreamReader file = new System.IO.StreamReader(path +" \\程序名.txt", System.Text.Encoding.GetEncoding("gb2312"));
text = file.ReadLine();
}
public Form1()
{
InitializeComponent();
readconfig();
this.Visible = false;
}
private void timer1_Tick(object sender, EventArgs e)
{
this.Visible = false;
MyProcesses = Process.GetProcessesByName(text);//需要监控的程序名,该方法带出该程序所有用到的进程
if (MyProcesses.Length == 0)//程序未运行,启动程序,并等待5000ms
{
try
{
Process.Start(@path + " \\" + text + ".exe");// 路径中带有反斜杠 要加 “@”
System.Threading.Thread.Sleep(2000);
}
catch (Exception ex)
{
this.timer1.Enabled = false;
MessageBox.Show(ex.ToString());
this.Close();
}
}
}
}
}
program代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;
using System.Threading;
namespace 监测自启动
{
static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
//获取指定的进程名
Process[] prProcesses =System.Diagnostics.Process.GetProcessesByName(Application.ProductName);
//如果获取的进程名多于一个
if (prProcesses.Length > 1)
{
try
{
//关闭全部进程
foreach (Process thisproc in prProcesses)
{
thisproc.Kill();
}
Restart();
}
catch (Exception Exc)
{
MessageBox.Show(Exc.Message);
}
//退出
}
Application.Run(new Form1());
}
private static void Restart()
{
Thread thtmp = new Thread(new ParameterizedThreadStart(run));
object appName = Application.ExecutablePath;
Thread.Sleep(1000);
thtmp.Start(appName);
}
private static void run(object obj)
{
Process ps = new Process();
ps.StartInfo.FileName = obj.ToString();
ps.Start();
}
}
}
VS2019工程文件下载地址:https://download.csdn.net/download/A254681448/12719437