Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kill process started with System.Diagnostic.Process.Start("FileName")

Tags:

c#

.net

vb.net

I am trying to create an app that will perform actions on specific times (much like the Windows Task Scheduler). I am currently using Process.Start() to launch the file (or exe) required by the task.

I am initiating a process by calling a file (an .mp3) and the process starts WMP (since it is the default application). So far so good. Now I want to kill that process. I know that it is normal behavior for the Process.Start(string, string) to return nothing (null in C#) in this case.

So I am asking how can I close WMP when I called it through Process.Start(string, string)??

Edit:

Please note that I am not opening WMP directly with Process.Start() and this is the line with which I run the process:

VB: Me._procs.Add(Process.Start(Me._procInfo))

C#: this._procs.Add(Process.Start(this._procInfo))

_procInfo is a ProcessStartInfo instance. _procInfo.FileName is "C:\route\myFile.mp3". That is why WMP opens. In any case, all of the Start() methods, except for the instance-one which returns a boolean, return nothing (null in C#), because WMP is not the process that was directly created (please note that WMP is run and the song does play).

like image 774
PedroC88 Avatar asked Oct 02 '10 20:10

PedroC88


2 Answers

Process.Start(string,string) returns you a Process resource that you can use to further control the new process.

Process newProcess = Process.Start("param1", "param2");
if (newProcess != null && !newProcess.HasExited)
  newProcess.Kill();

The same structure works if you use Process.Start(string), or any other static Process.Start overload.

Process.Start() is a member function and associates a new or reused Process with the Process component identified by this. Behaviour of this method depends on the properties of the Process identified by this.

like image 174
Steve Townsend Avatar answered Oct 15 '22 21:10

Steve Townsend


Don't do it this way.

It's not clear whether the intent of your program is 'Always launch with Windows Media Player' or 'Launch with the registered MP3 player', which might be, say, iTunes.

If you need WMP, use Process.Start with the full path to windows media player.

If you need the registed MP3 player, you can find out the correct exe using the code shown here. Again, start the process with this exe path, passing the MP3 as a parameter.

like image 44
Steve Cooper Avatar answered Oct 15 '22 22:10

Steve Cooper