2010-07-02 75 views
3

用C#編程.NET 4.0是我最新的熱情,我想知道如何添加功能到標準的Windows.Forms退出按鈕(表單右上角的紅色X)。將功能添加到Windows.Forms退出按鈕?

我找到了一種禁用按鈕的方法,但是由於我認爲它會影響用戶的體驗,所以我想改爲使用一些功能。

如何禁用退出按鈕:

#region items to disable quit-button 
    const int MF_BYPOSITION = 0x400; 
    [DllImport("User32")] 
    private static extern int RemoveMenu(IntPtr hMenu, int nPosition, int wFlags); 
    [DllImport("User32")] 
    private static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert); 
    [DllImport("User32")] 
    private static extern int GetMenuItemCount(IntPtr hWnd); 
    #endregion 

...

private void DatabaseEditor_Load(object sender, EventArgs e) 
    { 
     this.graphTableAdapter.Fill(this.diagramDBDataSet.Graph); 
     this.intervalTableAdapter.Fill(this.diagramDBDataSet.Interval); 

     // Disable quit-button on load 
     IntPtr hMenu = GetSystemMenu(this.Handle, false); 
     int menuItemCount = GetMenuItemCount(hMenu); 
     RemoveMenu(hMenu, menuItemCount - 1, MF_BYPOSITION); 
    } 

但如何在地球上我附上一個方法,應用程序退出時的標準退出按鈕之前。我想在退出Windows窗體之前先XmlSerialize List。

回答

4
private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e) 
{ 
    if(MessageBox.Show("Are you sure you want to exit?", "Confirm exit", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) 
    { 
     e.Cancel = true; 
    } 
} 
+0

Thanx Paul! 這樣做:) BR – 2010-07-02 07:46:06

+0

爲了記錄,事件被稱爲'FormClosing',所以當使用屬性檢查器添加方法時,它調用方法'Form1_FormClosing'。我無法弄清楚爲什麼沒有「閉幕」事件,並意識到它實際上是「FormClosing」。 – styfle 2011-10-31 16:34:29

5

如果你想形成閉合之前寫的代碼,使用的FormClosing事件

private void Form1_FormClosing(object sender, FormClosingEventArgs e) 
    { 

    } 
+0

感謝名單塞爾坎! 這樣做的訣竅:) BR – 2010-07-02 07:46:33

+0

歡迎您... – 2010-07-02 07:48:20

1

,我發現最好的方法實際上是創建一個事件處理程序,將調用要調用的方法。

在構造函數中:

this.Closed += new EventHandler(theWindow_Closed); 

然後創建方法:

private void theWindow_Closed(object sender, System.EventArgs e) 
{ 
    //do the closing stuff 
}