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();
}
}
}
}
精彩评论