-1

here is my code:

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();
        }
    }
}

the error I recieve is: "Error CS0103 The name 'myProcess1' does not exist in the current context" What I'm trying to do is to when the user clicks the kill button it will end the test.exe process. Is there any way to do this?

2 Answers2

2

You can't access myProcess1 outside of the using statement. The only way that you would be able to kill that process would be by setting myProcess1 up as a global variable. That being said, I would highly discourage going that route with processes. The best option would be to have the user select the process in the application so that you can ensure a running process prior to killing.

Wellerman
  • 846
  • 4
  • 14
1

As suggested, move the declaration of myProcess from local to class level:

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();
    }
}
Idle_Mind
  • 38,363
  • 3
  • 29
  • 40