Come posso impedire la chiusura della finestra mostrando un MessageBox
? (Tecnologia: WinForms
con C#
)
Quando si verifica l’evento close, voglio che venga eseguito il seguente codice:
private void addFile_FormClosing( object sender, FormClosingEventArgs e ) { var closeMsg = MessageBox.Show( "Do you really want to close?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Question ); if (closeMsg == DialogResult.Yes) { //close addFile form } else { //ignore closing event } }
private void Form1_FormClosing(object sender, FormClosingEventArgs e) { var window = MessageBox.Show( "Close the window?", "Are you sure?", MessageBoxButtons.YesNo); e.Cancel = (window == DialogResult.No); }
Cattura evento FormClosing e imposta e.Cancel = true
private void AdminFrame_FormClosing(object sender, FormClosingEventArgs e) { var res = MessageBox.Show(this, "You really want to quit?", "Exit", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2); if (res != DialogResult.Yes) { e.Cancel = true; return; } }
All’interno del tuo evento OnFormClosing
puoi mostrare la finestra di dialogo e if
risposta è falsa (non mostrare), quindi impostare la proprietà Cancel
di EventArgs
su true
.
Per prevenire o bloccare la chiusura del modulo in situazioni particolari puoi utilizzare questa strategia:
private void MyForm_FormClosing(object sender, FormClosingEventArgs e) { if (FLAG_CONDITION == true) { MessageBox.Show("To exit save the change!!"); e.Cancel = true; } }
Una svolta speciale potrebbe essere quella di impedire sempre all’utente solo la chiusura del modulo:
private void Frm_FormClosing(object sender, FormClosingEventArgs e) { e.Cancel = (e.CloseReason == CloseReason.UserClosing); // disable user closing the form, but no one else }
Direttamente da MSDN :
private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e) { // Determine if text has changed in the textbox by comparing to original text. if (textBox1.Text != strMyOriginalText) { // Display a MsgBox asking the user to save changes or abort. if(MessageBox.Show("Do you want to save changes to your text?", "My Application", MessageBoxButtons.YesNo) == DialogResult.Yes) { // Cancel the Closing event from closing the form. e.Cancel = true; // Call method to save file... } } }
Nel tuo caso non devi fare nulla per chiudere esplicitamente il modulo. A meno che tu non lo annulli, si chiuderà automaticamente, quindi il tuo codice sarà:
private void addFile_FormClosing( object sender, FormClosingEventArgs e ) { var closeMsg = MessageBox.Show( "Do you really want to close?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Question ); if (closeMsg == DialogResult.Yes) { // do nothing } else { e.Cancel = true; } }