2010-01-29 39 views
10

如果我運行下面的代碼:Process.Exited並不總是射擊

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 
} 

,當我退出記事本事件引發。如果我嘗試使用相同的代碼,但是我開始使用相同的代碼:

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 
} 

事件永遠不會被解僱。是否因爲加載圖像的過程永遠不會關閉?

UPDATE:開始該過程並不總是一個圖像。它可以是任何東西(pdf,word文檔等)。也許我的做法是不正確的。在用戶退出過程之後是否有其他方式來刪除文件?

謝謝

回答

7

我會使用臨時文件。有函數來創建一個臨時文件...

你的事件不是由於缺乏對過程本身的射擊,我猜。您可以嘗試使用shell來「啓動」有問題的文檔,但不保證所有類型的文件都有處理程序。

+0

是的,我認爲這是一個過程中的問題。Thx的幫助 – 2010-10-27 00:04:07

0

事件以Microsoft Viewer作爲查看器激發我。您是否可能使用實際上並未關閉的查看器?

+2

這是奇怪的。我已經測試了Windows 7和Vista上的代碼,並且事件從未被解僱。該過程啓動默認的Windows照片查看器 – 2010-01-29 15:04:37

+0

您的程序在事件觸發之前退出。 – rerun 2010-01-29 15:37:01

+0

否。如果將文件路徑的代碼更改爲word文檔,則會觸發該事件。這是Windows照片查看器真正的問題。 您試過什麼操作系統? – 2010-01-29 15:46:27

1

由於圖像文件不可執行,因此您正在Windows中使用默認圖像查看器。我改變了代碼使用XP的默認,它工作正常。

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(); 
    } 


} 
+1

不幸的是,我需要一個通用的方法。它可能並不總是一個圖像。它可以是PDF,Word文檔等。我已更新我的問題。 – 2010-01-29 15:03:35

4

的Windows Media Player嘗試下面的代碼

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

對於Windows圖片查看器試試這個

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

現在都將給您的退出事件在Windows 7

15

您應該啓用提高該過程的事件。

process_name.EnableRaisingEvents = true; 
+3

他在他的代碼雖然 – 2012-09-27 06:48:24

+3

雖然我忘記了我的代碼,這個答案幫了我;) – ensisNoctis 2016-03-17 16:01:41