Alexandre Pepin
Alexandre Pepin

Reputation: 1836

Process.Exited not always firing

If I run the following code :

Process myProcess = new System.Diagnostics.Process();
myProcess.StartInfo.FileName = "notepad.exe";
myProcess.EnableRaisingEvents = true;
myProcess.Exited += new System.EventHandler(Process_OnExit);
myProcess.Start();

public static void Process_OnExit(object sender, EventArgs e)
{
    // Delete the file on exit
}

The event is raised when I exit notepad. If I try the same code, but I start an image instead :

Process myProcess = new System.Diagnostics.Process();
myProcess.StartInfo.FileName = @"C:\Users\Public\Pictures\Sample Pictures\Desert.jpg";
myProcess.EnableRaisingEvents = true;
myProcess.Exited += new System.EventHandler(Process_OnExit);
myProcess.Start();

public static void Process_OnExit(object sender, EventArgs e)
{
    // Delete the file on exit
}

The event is never fired. Is it because the process that loads the image is never closed ?

UPDATE : The process to start is not always an Image. It can be anything (pdf, word document, etc). Maybe my approach isn't right. Is there any other way to delete the file after the user exited the process ?

Thank you

Upvotes: 12

Views: 15254

Answers (4)

s.ukreddy
s.ukreddy

Reputation: 314

you should enable raising events for the process.

process_name.EnableRaisingEvents = true;

Upvotes: 18

Sujith Kumar
Sujith Kumar

Reputation: 51

For windows media player try the following code

 myProcess.StartInfo.FileName = "wmplayer";
 myProcess.StartInfo.Arguments = "yourfilename";

For windows picture viewer try this

 myProcess.StartInfo.FileName = @"rundll32.exe";
 myProcess.StartInfo.Arguments = @"C:\Windows\System32\shimgvw.dll,ImageView_Fullscreen " + yourfilepath;

Now both will give your exited event in Windows 7

Upvotes: 5

Gyuri
Gyuri

Reputation: 4892

I would use a temp file. There are functions to create a temp file...

Your event is not firing due to the lack of the process itself, I guess. You can try to use the shell to "start" the document in question but nothing guarantees that there will be a handler for all types of files.

Upvotes: 7

rerun
rerun

Reputation: 25505

You are using the default image viewer in windows since an image file is not executable. I changed the code to use the XP default and it worked fine.

class Program
{
    static void Main(string[] args)
    {
        Process myProcess = new System.Diagnostics.Process(); 
        myProcess.StartInfo.FileName = @"rundll32.exe"; 
        myProcess.EnableRaisingEvents = true;
        myProcess.StartInfo.Arguments = @"C:\winnt\System32\shimgvw.dll,ImageView_Fullscreen c:\leaf.jpg";
        myProcess.Exited += new System.EventHandler(Process_OnExit); 
        myProcess.Start();
        Console.Read();



    }
    public static void Process_OnExit(object sender, EventArgs e)
    {
        Console.WriteLine("called");
        Console.Read();
    } 


}

Upvotes: 1

Related Questions