2012-11-13 65 views
3

我需要以相同的方式關閉我的應用程序,無論是直接關閉還是關閉任務欄或任務管理器。我需要做一些預先設置,並在應用程序關閉之前每次自動生成日誌文件...如何管理我的應用程序關閉的方式?

例如,我在每次退出時對我的應用程序表單產生以下影響,但是當I關閉我的應用程序從任務欄或任務管理器...

System.Windows.Forms.Timer closeTimer = new System.Windows.Forms.Timer(); 

    void lblClose_Click(object sender, System.EventArgs e) 
    { 
     closeTimer.Tick += new EventHandler(closeTimer_Tick); 
     closeTimer.Interval = 10; 
     closeTimer.Start();    
    } 

    void closeTimer_Tick(object sender, EventArgs e) 
    { 
     int a = (int)(this.Opacity * 100); 
     a--; 
     this.Opacity = ((double)a/100); 
     if ((this.Opacity*100) == 0) 
      this.Close(); 
    } 
+1

也許這個問題會很有用:http://stackoverflow.com/questions/10579446/capturing-application-exit-event-winforms – Mansfield

+0

'System.Windows.Forms.Form'有兩個事件'FormClosing'和'FormClosed '你可以在這種情況下使用。 – Leri

+0

@PLB這隻會捕獲窗體關閉 - 這並不一定意味着應用程序正在關閉。 – Mansfield

回答

0

您需要處理FormClosing事件。 這裏更多的信息: http://msdn.microsoft.com/en-us/library/system.windows.forms.form.formclosing.aspx

+0

正如我在評論中所說,這不保證**應用程序**正在關閉,只有表格。 – Mansfield

+0

@Mansfield - 還有很多方法可以以這種方式關閉應用程序,ProcessExit事件也不會拋出。 –

+0

@Ramhound粗魯地終止了這個過程,是的。這不是絕對的 - 但它比使用FormClose更好。我承認,我濫用保證一詞。 – Mansfield

5

this question

[STAThread] 
static void Main() 
{ 
    Application.EnableVisualStyles(); 
    Application.SetCompatibleTextRenderingDefault(false); 
    Application.ApplicationExit += new EventHandler(Application_ApplicationExit); 
    AppDomain.CurrentDomain.ProcessExit += new EventHandler(CurrentDomain_ProcessExit); 
    Application.Run(new MainForm()); 
} 

這是優於使用FormClosed作爲僅僅因爲一個窗體關閉並不一定意味着該應用程序(具體到你的課程代碼)。

+0

+1爲ProcessExit,沒有想到這一點。 –

+0

謝謝,這真的很有幫助.. –

相關問題