Reputation:
I'm using C# WPF.
I have list of Process that i run them with Start()
command.
I want to know when the user exit from the process and to catch the event.
What i'm tried:
myProcess.StartInfo.FileName = fileName;
myProcess.EnableRaisingEvents = true;
myProcess.Exited += new EventHandler(myProcess_Exited);
myProcess.Start();
*myProcess is Process object.
The problem is immediately after Start()
command the application is closed and myProcess_Exited
callback called.
Where is my mistake?
Upvotes: 5
Views: 5615
Reputation: 2180
myProcess.StartInfo.FileName = fileName;
myProcess.EnableRaisingEvents = true;
myProcess.Exited += new EventHandler(myProcess_Exited);
myProcess.Start();
myProcess.WaitForExit();
Or,
myProcess.WaitForExit(timeout);
Upvotes: -1
Reputation: 21138
The only reason for that behaviour is, that the exe you start is closing or crahsing directly after starting it. For example if the exe is a console
application which does not have any user-input or some thing else. Try your code with Notepad.exe
and you'll see it works.
Take a look at this IronPython
code, which is mainly .net code as your application (only easier for testing purpose):
from System.Diagnostics import Process
def on_exit(s, e):
print ('Exited')
process = Process()
process.StartInfo.FileName = "C:\\Windows\\System32\\notepad.exe"
process.EnableRaisingEvents = True
process.Exited += on_exit;
process.Start()
Exit is called if i close Notepad.
EDIT
If you want to detected which app was closed/exited, just case your sender
object to Process
and access it's FileName
over StartInfo
. For example:
private void OnExited(object sender, EventArgs, e)
{
var process = (sender as Process);
Console.WriteLine(process.StartInfo.FileName);
}
Hope this helps.
Upvotes: 8