打开进程关闭进程方法1
打开关闭进程的代码如下:
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;
namespace process2
{
public partial class Form1 : Form
{
static string rootpath = "notepad.exe";
static string rootpath2 = "calc.exe";
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Process.Start(rootpath);
}
private void button2_Click(object sender, EventArgs e)
{
//Process[] processes=Process.GetProcessesByName(Path.GetFileNameWithoutExtension(rootpath));
Process[] processes = Process.GetProcessesByName("notepad");
foreach (Process process in processes)
{
try
{
process.Kill();
}
catch (Exception ex)
{
// 处理无法终止进程的情况
MessageBox.Show($"Failed to kill process {process.Id}: {ex.Message}", "Error");
}
}
}
}
}
下面两个方法是一样的,都是为了获取进程的名称。
//Process[] processes=Process.GetProcessesByName(Path.GetFileNameWithoutExtension(rootpath));
Process[] processes = Process.GetProcessesByName("notepad");
打开进程关闭进程方法2
using System.Windows.Forms;
using System.Diagnostics;
using System.Threading;
namespace process
{
public partial class Form2 : Form
{
Process calcProcess;
public Form2()
{
InitializeComponent();
}
private void btn_Start_Click(object sender, EventArgs e)
{
calcProcess = new Process();
//calcProcess.StartInfo.FileName = @"C:\Windows\system32\calc.exe";
calcProcess.StartInfo.FileName = @"C:\Windows\notepad.exe";
calcProcess.Start();
if (calcProcess != null && !calcProcess.HasExited)
{
MessageBox.Show($"The process '{calcProcess.Id}' is running.");
}
else
{
MessageBox.Show($"The process '{calcProcess.ProcessName}' is not running.");
}
}
private void btn_Stop_Click(object sender, EventArgs e)
{
if (calcProcess != null && !calcProcess.HasExited)
{
try
{
calcProcess.CloseMainWindow();
Thread.Sleep(1000);
}
catch (Exception ex)
{
MessageBox.Show($"Failed to close or kill the process: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
else
{
MessageBox.Show("Calculator process is not running.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
}
关闭进程可以使用calcProcess.CloseMainWindow();也可以使用calcProcess.Kill();