How to cancel closing winform? - c#

When closing form, FormClosed event occurs, and I want to put some work when FormClosed event occurs like:
this.FormClosed += (s, e) => {
var result = MessageBox.Show("Exit Program?", "Exit?", MessageBoxButtons.YesNo, MessageBoxIcons.Question);
if (result == DialogResult.No) {
return;
} else {
// Do some work such as closing connection with sqlite3 DB
Application.Exit();
}
};
The problem is that no matter I choose yes or no in the messagebox, the program gets closed. I need to abort program exit if I choose no, so how do I do that?

The FormClosing (as opposed to your FormClosed) event's FormClosingEventArgs contains a Cancel boolean that you can change to true. Note that this will occur even if you close the form programmatically.
this.FormClosing += (s, e) => {
var result = MessageBox.Show("Exit Program?", "Exit?", MessageBoxButtons.YesNo, MessageBoxIcons.Question);
if (result == DialogResult.No) {
e.Cancel = true;
} else {
// Do some work such as closing connection with sqlite3 DB
Application.Exit();
}
};
To determine how the form was closed, it also includes a CloseReason.
See docs here and here.

You can't use the FormClosed event, you need to use the FormClosing event and set e.Cancel to true.
The reason for that is that the FormClosed event occurs after the form has been closed, while the FormClosing event occurs as the form is being closed.
The FormClosingEventArgs class contains a boolean property called Cancel that you can set to true to stop the form from being closed.

Related

C# Windows Form formclosing error

i am pretty newbie for coding. Here is i am having a problem:
private void pano_FormClosing(object sender, FormClosingEventArgs e)
{
DialogResult dialog = MessageBox.Show("Uygulamadan çıkış yapmak istediğinizden emin misiniz?", "Çıkış", MessageBoxButtons.YesNo);
if (dialog == DialogResult.Yes)
{
Application.Exit();
}
else if (dialog == DialogResult.No)
{
e.Cancel = true;
}
My purpose with this code block to ask user "are sure to quit" but unfortunetly when i close the application, i got notification window for 3 times? Is there any idea why thats happening or any solution?
Thanks a lot.
Nuri.
Firstly, as Steve pointed out, remove the 'Yes' part - if not explicitly canceled, the event will close that form as a result of clicking.
Now, for the problem of yours. Seems like your alert is called twice. I was able to solve that easily by making a static bool close_alert_shown, and when the first alert is shown, set it to true so that the next alert won't pop up.
Final code looks like that:
if (close_alert_shown) return;
close_alert_shown = true;
DialogResult dialog = MessageBox.Show("Uygulamadan çıkış yapmak istediğinizden emin misiniz?", "Çıkış", MessageBoxButtons.YesNo);
if (dialog == DialogResult.No)
{
e.Cancel = true;
close_alert_shown = false;
}
And on the top of the form (before the public Form1() contructor line):
static bool close_alert_shown = false;
What i suspect is when application is exiting, it is again calling form closing since we have subscribed for that event. I assume, simple fix would be unsubscribe from the event before calling exit.
this.FormClosing-=Form1_FormClosing;
Application.Exit();

Button is closing WindowsForm automatically

I have a WinForms application that checks for pending changes whenever the user hits the cancel button. If there are pending changes, I prompt the user to see if they are sure they wish to cancel. If they do, I close the form. If not, I just return. However, the form is closing anyways. After some debugging, I realized it was because this particular button is set to the form's CancelButton, so clicking it caused the form to close. To verify, I removed the CancelButton property, but the behavior persisted.
How can I prevent this automatic closing? Here is my event handler code:
private void closeButton_Click(object sender, EventArgs e)
{
DialogResult dr = DialogResult.Yes;
if (changesMade)
{
dr = MessageBoxEx.Show(this, "Are you sure you wish to disregard the changes made?", "Changes Made", MessageBoxButtons.YesNo);
}
if (dr == DialogResult.Yes)
{
Close();
}
else
{
//TODO:
}
}
In the above code, the form should only close if there are no changes made, or if the user chose to disregard them. I made changes, and clicked 'No' to the DialogBox, but the form still closed. With and without the button set as the form's CancelButton.
Just set the property DialogResult of the form to the enum DialogResult.None
....
if (dr == DialogResult.Yes)
{
Close();
}
else
{
this.DialogResult = DialogResult.None;
}
or simply:
if (dr != DialogResult.Yes)
this.DialogResult = DialogResult.None;
The form closes automatically because the property DialogResult of the button is not set to DialogResult.None in the Forms Designer. In this scenario, the WinForms engine takes that value and assign it to the DialogResult property of the whole form causing it to automatically close. This is usually used in the calling code of the form to distinguish between a Confirm and a Cancel button
In the example below suppose that on the frmCustomers there are two buttons, one with the DialogResult property set to DialogResult.OK and another set to DialogResult.Cancel. Now if the user hits the OK button you know, in the calling code what to do with the inputs for your new customer
using(frmCustomers f = new frmCustomers())
{
if(f.ShowDialog() == DialogResult.OK)
{
// Execute code to save a customer
}
}
Following up on my comment, this is what I do for an internal tool I wrote recently:
private void Form_FormClosing(object sender, FormClosingEventArgs e)
{
e.Cancel = !PromptUnsavedChanges();
}
private bool PromptUnsavedChanges()
{
if (HasFormChanged()) //checks if form is different from the DB
{
DialogResult dr = MessageBox.Show("You have unsaved changes. Would you like to save them?", "Unsaved Changes", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
if (dr == System.Windows.Forms.DialogResult.Yes)
tsmiSave_Click(null, null); // Saves the data
else if (dr == System.Windows.Forms.DialogResult.Cancel)
return false; // Cancel the closure of the form, but don't save either
}
return true; // Close the form
}
The logic could probably cleaned up from a readability point of view, now that I'm looking at it months later. But it certainly works.
With this you simply just call this.Close(); in your button click event. Then that event is what handles the prompting and decides if it should actually close or not.

Why isnt my windows form closing?

Im playing about with some very simple windows forms. I have an event handler for a form close event that asks the user whether they want to save what they've typed:
private void closeNpForm(object sender, FormClosingEventArgs e)
{
if (!saveFlag)
{
if (MessageBox.Show("Do you want to save the text entered?", "Save Changes?", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
e.Cancel = true;
saveFlag = true;
writeToFile(this.allText.Text);
}
}
}
if the user clicks yes (indicating they do want to save their text) i call the writeToFile method, and also set a flag so as not to ask them to save again:
private void writeToFile(string text)
{
writer = new StreamWriter("inputdata.txt");
writer.Write(text);
writer.Close();
this.Close();
}
As far as i can see, the writeToFile method should close the form when its finished. But this isnt happening, when i run the writeToFile method, the form just stays open. Can anyone tell me what im doing wrong?
as i understand it, calling this.Close() should trigger a form closing event, calling my event handler, due to the flag now being true, the form should just close without a problem.
note, my parent class extends the Form class, so im just using this to refer to my form instance.
e.Cancel = true -- whoops. The event is told cancel (read: not close the window).
I suspect that because close() is being called from within the close event and there is some internal clobbering going on (either suppressed or the Cancel is propagated over, etc). Just clean up the code (saving to the file has nothing to do with closing the window although the file might be saved and the window closed from within a button event.)
Happy coding.
writing to file and closing the form are two different kinds of operations. you should not have this.Close() in your writeToFile method.
As pst says, by setting e.cancel to true, you are basically telling the CloseForm event to be cancelled, therefore it's not closing once it exits from the closeNpForm event handler.
After exiting closeNpForm, the form checks for the Cancel property of the event and will not actually proceed with closing itself.
Why are you cancelling the close event and then calling writeToFile that closes the form?
In addition to what #pst said, why are you setting Cancel = true if you don't want to cancel the closing of the form?
If you remove e.Cancel = true; and this.Close(); it should do what you want.
This works for me:
public class Form1 : Form
{
bool saveFlag;
private void Form1_Load(object sender, EventArgs ev)
{ FormClosing += closeNpForm;
}
private void closeNpForm(object sender, FormClosingEventArgs e)
{
if (!saveFlag)
{
if (MessageBox.Show("Do you want to save the text entered?", "Save Changes?", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
e.Cancel = true;
saveFlag = true;
this.Close();
}
}
}
}

How to have two versions of an event handler?

I have an event handler subscribed to the FormClosing event. This event handler provides dialog for the user when they exit my application; like so:
private void frmUavController_FormClosing(object sender, System.ComponentModel.CancelEventArgs e)
{
DialogResult dlgResult = MessageBox.Show("Are you sure you want to exit?", "Exit?",
MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (dlgResult == DialogResult.Yes)
{
UtilSTKScenario.PauseScenarioAnimation(UtilSTKScenario._stkObjectRoot);
}
else if (dlgResult == DialogResult.No)
{
e.Cancel = true;
}
}
Because the application runs in a side-by-side fashion; injecting COM commands into another application - I want my application to exit if the application receiving COM commands is not launched (or closed during execution). This is achieved like so:
static UtilSTKScenario()
{
// give time for active form to show
Thread.Sleep(100);
_stkProgramId = ConfigurationManager.AppSettings.Get("stkProgramId");
if (CheckIfStkIsLaunched())
{
InitAllFields();
}
else
{
HideController dHideController = new HideController(((frmUavController)Form.ActiveForm).HideControllerUi);
((frmUavController)Form.ActiveForm).Invoke(dHideController);
Application.Exit();
}
}
Calling 'Application.Exit()' causes the FormClosing event to fire. This I do not want - rather, I want the application to just exit.
Any ideas ?
WulfgarPro
You might be able to look at the event args of the FormClosing event. FormClosingEventArgs has a CloseReason property that may give an indicator if the form was closed by a user directly as opposed to some other mechanism.
Though I'm not clear how Application.Exit() calls will appear... If it is also showing as CloseReason.UserClosing then you may need to add an overload to your form [e.g. SystemClose()] to close your form and use an instance variable to tell it not to prompt within your handler.
Your FormClosing event gets a FormClosingEventArgs parameter, which has a CloseReason property. If that's CloseReason.ApplicationExitCall, then the form is closing because of a call to Application.Exit. You can just skip your "close?" prompt in that case.
private void frmUavController_FormClosing(object sender, FormClosingEventArgs e)
{
if (e.CloseReason == CloseReason.ApplicationExitCall)
return;
// ...
The typical way to handle this sort of thing (bypass normal "do you want to close?" checks) is to use a Boolean variable. Name it something like _forceExit, set it to true if the external event forces you to close, and if it's true, skip the dialog box in your Closing event.
Can you look at the sender object? My guess is that the sender object is different depending on you actually close the form or call the Application.Exit() method.

Preventing a dialog from closing in the button's click event handler

I have a dialog that I show with <class>.ShowDialog(). It has an OK button and a Cancel button; the OK button also has an event handler.
I want to do some input validation in the event handler and, if it fails, notify the user with a message box and prevent the dialog from closing. I don't know how to do the last part (preventing the close).
You can cancel closing by setting the Form's DialogResult to DialogResult.None.
An example where button1 is the AcceptButton:
private void button1_Click(object sender, EventArgs e) {
if (!validate())
this.DialogResult = DialogResult.None;
}
When the user clicks button1 and the validate method returns false, the form will not be closed.
Given that you've specified you want a pop error dialog, one way of doing this is to move your validation into a OnClosing event handler. In this example the form close is a aborted if the user answers yes to the question in the dialog.
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...
}
}
}
By setting e.Cancel = true you will prevent the form from closing.
However, it would be a better design/user experience to display the validation errors inline (via highlighting the offending fields in some way, displaying tooltips, etc.) and prevent the user from selecting the OK button in the first place.
Don't use the FormClosing event for this, you'll want to allow the user to dismiss the dialog with either Cancel or clicking the X. Simply implement the OK button's Click event handler and don't close until you are happy:
private void btnOk_Click(object sender, EventArgs e) {
if (ValidateControls())
this.DialogResult = DialogResult.OK;
}
Where "ValidateControls" is your validation logic. Return false if there's something wrong.
You can catch FormClosing an there force the form to remain opened.
use the Cancel property of the event argument object for that.
e.Cancel = true;
and it should stop your form from closing.
This doesn't directly answer your question (other already have), but from a usability point of view, I would prefer the offending button be disabled while the input is not valid.
Use this code:
private void btnOk_Click(object sender, EventArgs e) {
if (ValidateControls())
this.DialogResult = DialogResult.OK;
}
The problem of it is that the user has to clic two times the buttons for closing the forms;
Just add one line in the event function
private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e)
{
this->DialogResult = System::Windows::Forms::DialogResult::None;
}
I wish I had time to find a better example, but you would be much better off using the existing windows forms validation techniques to do this.
http://msdn.microsoft.com/en-us/library/ms229603.aspx
void SaveInfo()
{
blnCanCloseForm = false;
Vosol[] vs = getAdd2DBVosol();
if (DGError.RowCount > 0)
return;
Thread myThread = new Thread(() =>
{
this.Invoke((MethodInvoker)delegate {
picLoad.Visible = true;
lblProcces.Text = "Saving ...";
});
int intError = setAdd2DBVsosol(vs);
Action action = (() =>
{
if (intError > 0)
{
objVosolError = objVosolError.Where(c => c != null).ToArray();
DGError.DataSource = objVosolError;// dtErrorDup.DefaultView;
DGError.Refresh();
DGError.Show();
lblMSG.Text = "Check Errors...";
}
else
{
MessageBox.Show("Saved All Records...");
blnCanCloseForm = true;
this.DialogResult = DialogResult.OK;
this.Close();
}
});
this.Invoke((MethodInvoker)delegate {
picLoad.Visible = false;
lblProcces.Text = "";
});
this.BeginInvoke(action);
});
myThread.Start();
}
void frmExcellImportInfo_FormClosing(object s, FormClosingEventArgs e)
{
if (!blnCanCloseForm)
e.Cancel = true;
}
You can probably check the form before the users hits the OK button. If that's not an option, then open a message box saying something is wrong and re-open the form with the previous state.

Categories

Resources