21

I need to close another Process (Windows Media Encoder) from a C# Application ,and so far i can do it with:

Process.GetProcessesByName("wmenc.exe")[0].CloseMainWindow();

But if the Media Encoder Application is Streaming or Recording it shows a Dialog on exit:

"Are you sure you want to stop encoding?"

So is there a way to answer or click Yes button from Code?

[Edit] Many users are answering with Process.kill() ,but that is not an Option ,because Process.Kill(); will Terminate Windows Media Encoder immediately ,and Windows Media Encoder will not Finalize the File which is Writing ,which forces me to Reindex the Video File .So no i cannot use Process.Kill();

Rosmarine Popcorn
  • 10,761
  • 11
  • 59
  • 89
  • Don't bother about closing any windows. Better look for ways to force the process be killed. What if it opened another window? The process won't quit if any of the associated windows is open – Dercsár May 18 '11 at 15:07
  • I believe the processes retrieved by GetProcessesByName should be disposed, BTW. http://stackoverflow.com/questions/16957320/what-does-process-dispose-actually-do – BlueMonkMN Oct 30 '14 at 15:46
  • I'm not sure who closed this as a duplicate, but the questions have nothing to do with one another and this question is not answered in any way by the target question. – Dave Ross Apr 26 '22 at 13:28

2 Answers2

10
Process[] runningProcesses = Process.GetProcesses();
foreach (Process process in runningProcesses)
{
    // now check the modules of the process
    foreach (ProcessModule module in process.Modules)
    {
        if (module.FileName.Equals("MyProcess.exe"))
        {
            process.Kill();
        } else 
        {
         enter code here if process not found
        }
    }
}
Floern
  • 33,559
  • 24
  • 104
  • 119
Alberich Drago
  • 129
  • 1
  • 7
6

Iterating through ProcessModule.filename triggered "Access denied" exception, however the following code worked fine.

Process[] runningProcesses = Process.GetProcesses();
foreach (Process process in runningProcesses)
{
    if (process.ProcessName == PROC_NAME)
        process.CloseMainWindow();
}
Martin
  • 3,396
  • 5
  • 41
  • 67
  • 2
    In some cases it's better than Kill - for example killing excel may corrupt opened file, CloseMainWindow has no such side effect – sarh Mar 11 '22 at 15:59