0

i want open(or create process) directory specific location and close(or kill process)

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 WindowsFormsApplication4
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        Process ps;

        private void button1_Click(object sender, EventArgs e)
        {
            ps = Process.Start("explorer.exe", @"C:\test");
            MessageBox.Show(ps.Id.ToString());
        }

        private void button2_Click(object sender, EventArgs e)
        {
            ps.Kill();
        }
    }
}

but an error occurred "Cannot process request because the process has exited."


edit

i want create process ("explorer.exe C:\test") (click button 1) and kill process made infront of (click button 2). "click button 1" then "click button 2".

i predict "Process ps = Process.Start("explorer.exe C:\test");" can kill like "ps.Kill()".

but already ps(Process variable) is disappear(killed?) and can't kill created directory process("explorer.exe",@"C:\test").

how to kill i created(or start) explorer.exe process


how to kill process created by Process.Start("explorer.exe")?

  • Does this answer your question? [How to kill a process without getting a "process has exited" exception?](https://stackoverflow.com/questions/13564645/how-to-kill-a-process-without-getting-a-process-has-exited-exception) – Martheen Oct 27 '20 at 02:30
  • @Martheen Not what i wanted and edit question, thanks – NANGMANBOT Oct 27 '20 at 02:52

2 Answers2

0

Please try this code.

Process processToKill = Process.GetProcessById(ps.Id);
processToKill.Kill();

You can use Process.GetProcessById() to get the currently running processes, then Process.Kill() to kill a process.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • Thread.Sleep(3000); //Stop responding for 3 seconds if (ps .HasExited) //Continue if the process has exited { //The process has exited //Console.WriteLine("The process has exited"); } else //Continue if the process has not exited { //myProcess.CloseMainWindow(); //Close the main Window ps .Kill(); //Terminate the process } – Rakesh Dhamejani Oct 27 '20 at 09:25
  • when button2_click, ps.HasExited always return true. i try to find ps.ID in process list but already killed. Process.Start("explorer.exe") create another process that's why can't find ps.ID in process list. have any way kill process created by Process.Start("explorer.exe")? – NANGMANBOT Oct 28 '20 at 05:35
0

You can use

foreach (Process p in Process.GetProcessesByName("processname"))
{
   p.Kill();
}

or

public Process something;
-------------------------
something = Process.Start("cmd.exe");
something.Kill();
Arkinetic
  • 1
  • 3