Abhishek
Abhishek

Reputation: 997

Closing process start from windows application on application close or exit

I am working on windows application. i have to run some window exe from my app, i am able to do the same but when i close my application these exe remains on running condition, i am not getting how can i close those exe. Please suggest some tips.

To run the Process

 private void StartChildProcess(string fileName)
    {
        Process newProcess = new Process();
        newProcess.StartInfo = new ProcessStartInfo(fileName); ;
        newProcess.Start();
        localProcess.Push(newProcess);
    }

To close the process

 private void CloseStartedProcesses()
    {
        while (localProcess.Count > 0)
        {
            Process process = localProcess.Pop();
            if (process != null && !process.HasExited)
            {
                process.CloseMainWindow();
                process.Close();
            }
        }
    }

Upvotes: 1

Views: 3969

Answers (5)

Abhishek
Abhishek

Reputation: 997

Try this:

Process[] p = Process.GetProcessesByName("osk");
foreach (var item in p)
{
    item.Kill();
}

Upvotes: 1

Sascha Hennig
Sascha Hennig

Reputation: 2572

Use Windows API - P/Invoke. FindWindow() or EnumWindows() to get the window handle. Then you can send WM_CLOSE or WM_QUIT to end the application via the SendMessage() function.

Note that if the application checks for user input on exiting (like a MessageBox asking weather the user really wants to quit) the only option might be to send WM_DESTROY which would be equivalent to Process.Kill (at least in respects to causing data loss - I am not certain it is the absolute equivalent).

Upvotes: 1

CodingBarfield
CodingBarfield

Reputation: 3398

Some options:

  • Setup some communication system so the Main application can alert the other application to shutdown (read up on some WCF information or remoting)
  • Create a do.shutdown file and let the second application check if that file exists, simple but efficient.
  • Use the process.Kill options
  • Use Sendkey or equivalent to send a 'quit' key combination

Upvotes: 1

Brijesh Mishra
Brijesh Mishra

Reputation: 2748

try this Process proc = Process.GetProcessesByName("processname"); proc.Kill();

Upvotes: 0

Shai
Shai

Reputation: 25619

The reason that the EXE you've ran from your application doesn't terminate once you close your application is probably because the 2nd application runs as a DIFFERENT, SEPARATE process.

If you run another process with System.Diagnostics.Process, it will remain in background until terminated manually or until it finishes it's job.

Upvotes: 0

Related Questions