如何解决我将如何在 winform 应用程序中终止循环之外的进程?
这是我的代码:
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();
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。