我在C#.net中有一個windows窗體應用程序,我想通過X按鈕關閉窗體時備份所以我在代碼下面寫下了這個動作。但是當我運行程序我注意到這個事件執行2次請幫我解決這個問題爲什麼Form_FormClosing事件在c#.net中執行2次
private void MenuFrm_FormClosing(object sender, FormClosingEventArgs e)
{
// DialogResult dialogResult = MessageBox.Show("ایا مایل به گرفتن نسخه پشتیبان می باشید", "هشدار", MessageBoxButtons.YesNo);
// if (dialogResult == DialogResult.Yes && !closefrm)
try
{
DialogResult dialogResult = MessageBox.Show("آیا مایل به خروج از نرم افزار میباشید؟", "خروج", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
SaveFileDialog f = new SaveFileDialog();
f.InitialDirectory = "D:\\";
f.Title = "HoghooghDastmozdBackup";
if (Directory.Exists("E:\\MobtakeranSoftBackup\\"))
{
f.FileName = "E:\\MobtakeranSoftBackup\\" + getPersianDate() + ".BAK";
f.FilterIndex = 1;
f.OverwritePrompt = true;
f.Filter = @"SQL Backup files (*.BAK) |*.BAK|All files(*.*) |*.*";
SqlConnection sqlconn = new SqlConnection(DBsetting.Connstring);
SqlCommand sqlcmd = new SqlCommand("BACKUP DATABASE HoghooghDastmozd TO DISK [email protected]", sqlconn);
sqlcmd.Parameters.AddWithValue("@n", f.FileName);
sqlconn.Open();
sqlcmd.ExecuteNonQuery();
sqlconn.Close();
Application.Exit();
}
else
{
Directory.CreateDirectory("E:\\MobtakeranSoftBackup\\");
f.FileName = "E:\\MobtakeranSoftBackup\\" + getPersianDate() + ".BAK";
f.FilterIndex = 1;
f.OverwritePrompt = true;
f.Filter = @"SQL Backup files (*.BAK) |*.BAK|All files(*.*) |*.*";
SqlConnection sqlconn = new SqlConnection(DBsetting.Connstring);
SqlCommand sqlcmd = new SqlCommand("BACKUP DATABASE HoghooghDastmozd TO DISK [email protected]", sqlconn);
sqlcmd.Parameters.AddWithValue("@n", f.FileName);
sqlconn.Open();
sqlcmd.ExecuteNonQuery();
sqlconn.Close();
Application.Exit();
}
}
else
{
e.Cancel = true;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
Application.Exit();
}
}
請確保您沒有連接兩個事件處理程序 - 在項目中搜索「MenuFrm_FormClosing」。您可能還想檢查FormClosingEventArgs的CloseReason,因爲這在Windows關閉時也會觸發。 – stuartd