问题描述
这是我的代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;
namespace Wraith
{
public partial class WraithClient : Form
{
public WraithClient()
{
InitializeComponent();
}
private void test_Click_1(object sender,EventArgs e)
{
using (Process myProcess1 = new Process())
{
myProcess1.StartInfo.UseShellExecute = false;
myProcess1.StartInfo.FileName = "test.exe";
myProcess1.StartInfo.CreateNowindow = true;
myProcess1.Start();
}
}
private void kill_Click(object sender,EventArgs e)
{
myProcess1.Kill();
}
}
}
我收到的错误是:“错误 CS0103 当前上下文中不存在名称‘myProcess1’” 我想要做的是当用户单击终止按钮时,它将结束 test.exe 进程。 有没有办法做到这一点?
解决方法
您不能在 myProcess1
语句之外访问 using
。您能够终止该进程的唯一方法是将 myProcess1
设置为全局变量。话虽如此,我非常不鼓励通过流程走这条路。最好的选择是让用户在应用程序中选择进程,这样您就可以在杀死进程之前确保进程正在运行。
按照建议,将 myProcess
的声明从本地移动到类级别:
private Process myProcess1;
private void test_Click_1(object sender,EventArgs e)
{
if (myProcess == null)
{
myProcess1 = new Process();
myProcess1.StartInfo.UseShellExecute = false;
myProcess1.StartInfo.FileName = "test.exe";
myProcess1.StartInfo.CreateNoWindow = true;
myProcess1.Start();
}
}
private void kill_Click(object sender,EventArgs e)
{
if (myProcess != null)
{
myProcess1.Kill();
}
}