My application appears to be skipping the Form_Closing event entirely, and I am not sure why. I have tried to debug it by using e.cancel and showing a messagebox when it closes, but the messagebox never shows, and the e.cancel doesnt cancel it. My code is
public void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (isClosed == false)
{
e.Cancel = true;
base.OnFormClosing(e);
this.Hide();
this.WindowState = FormWindowState.Minimized;
}
else
{
Application.Exit();
}
}
Thanks :)
Your method has the signature appropriate for a FormClosing event handler, but you are calling base.OnFormClosing which is only appropriate for an OnFormClosing override.
Pick one. For example, the override would look like
protected override void OnFormClosing(FormClosingEventArgs e)
{
if (isClosed == false)
{
e.Cancel = true;
base.OnFormClosing(e);
Hide();
WindowState = FormWindowState.Minimized;
}
else
{
Application.Exit();
}
}
Start by only using a message box to determine that you hace the right event
Then check the value of isclosed since I suspect it is true.
Related
We are currently upgrading and remodularizing our code as we transfer from 32 to 64 bit system. In due process, one of our goals is to change from an Init() function where things were added as such example.
this.Closing += new System.ComponentModel.CancelEventHandler(this.Form_Closing);
I'd like Windows events to handle these sorts of things. So I went to the Form_Closing event in the Windows Form Events and [without surprise] saw that this was not the form_closing event. My question to this is, is there any difference between what is actually going on with CancelEventArgs vs FormClosingArgs, or are these two pieces of code literally doing the same thing with one being a Component of System and one being the result of a Windows Event handling what it does best? I'm just sort of diving and indulging myself into this new project as an intern. Is it possible to just replace the CancelEventArgs with the FormClosing one without any loss of data or issues?
Code 1: CancelArgs
private void Form_Closing(object sender, CancelEventArgs e)
{
// If the user hit Cancel, just close the form.
if (this.DialogResult == DialogResult.Ignore)
return;
if (this.DialogResult == DialogResult.OK)
{
// If the address is not dirty, just cancel out of
// the form.
if (!this._editedObject.IsDirty)
{
this.DialogResult = DialogResult.Cancel;
return;
}
// Save changes. If save fails, don't close the form.
try
{
SaveChanges();
return;
}
catch (Exception ex)
{
ShowException se = new ShowException();
se.ShowDialog(ex, _errorObject);
_errorObject = null;
e.Cancel = true;
return;
}
}
Form_Closing -- Preferred Route
private void ScheduleItemDetail_FormClosing(object sender, FormClosingEventArgs e)
{
// If the user hit Cancel, just close the form.
if (this.DialogResult == DialogResult.Ignore)
return;
if (this.DialogResult == DialogResult.OK)
{
// If the address is not dirty, just cancel out of
// the form.
if (!this._editedObject.IsDirty)
{
this.DialogResult = DialogResult.Cancel;
return;
}
// Save changes. If save fails, don't close the form.
try
{
SaveChanges();
return;
}
catch (Exception ex)
{
ShowException se = new ShowException();
se.ShowDialog(ex, _errorObject);
_errorObject = null;
e.Cancel = true;
return;
}
}
}
You don't get the CloseReason property with the CancelEventArgs class, which is the only difference, since FormClosingEventArgs inherits from the CancelEventArgs class. The FormClosingEventArgs was introduced in .Net 2.0.
Alternatively, instead of using the event, you could just override the OnFormClosing method, too.
protected override void OnFormClosing(FormClosingEventArgs e) {
// your code
base.OnFormClosing(e);
}
Recently I had to edit my program code so that the form will close after creating a PDF. In FormClosing() there's a MessageBox.Show for closing or not, depending on the DialogResult. The problem is that when I try to Close(), it shows me the MessageBox, I need to close it without showing it. Thanks.
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (MessageBox.Show("Exit?", "Exit", MessageBoxButtons.YesNo) == DialogResult.No)
{
e.Cancel = true;
}
}
private void btn_PdfCreate_CloseForm_Click(object sender, EventArgs e)
{
showPDf();
// close pdf but skip MessageBox
}
You can stop listening to the event like so
private void btn_PdfCreate_CloseForm_Click(object sender, EventArgs e)
{
this.FormClosing -= Form1_FormClosing
showPDf();
Close();
}
You can use the CloseReason property of the FormClosingEventArgs:
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (e.ClosingReason == CloseReason.UserClosing && MessageBox.Show("Exit?", "Exit", MessageBoxButtons.YesNo) == DialogResult.No)
{
e.Cancel = true;
}
}
Use e.ClosingReason to find out if the formClosing event was fired by the user's attempt to close the form, or by something else.
for further reading, go to MSDN:
http://msdn.microsoft.com/en-us/library/system.windows.forms.formclosingeventargs.closereason(v=vs.110).aspx
You anyways want to close the form after pdf creation. So call Form's Dispose method just after pdf creation like below and no need of registering for the OnFormClosing event
private void btn_PdfCreate_CloseForm_Click(object sender, EventArgs e)
{
showPDf();
this.Dispose();
}
I overridden the FormClosing event to minimize to system tray when clicked. Here is my code:
private void OnFormClosing(object sender, FormClosingEventArgs e)
{
if (e.CloseReason == CloseReason.UserClosing)
{
e.Cancel = true;
this.Hide();
notifyIcon.BalloonTipText = "Server minimized.";
notifyIcon.ShowBalloonTip(3000);
}
else
{
this.Close();
}
}
And I also set the notifyIcon's DoubleClick event as well, here is the code:
private void showWindow(object sender, EventArgs e)
{
Show();
WindowState = FormWindowState.Normal;
}
I have two questions regarding this:
1) Now, when the upper-right "X" button is clicked, the application is minimized to the tray, but I can't close it (makes sense...). I wish to click right click on the icon in the system tray, and that it will open a menu with, let's say, these options: Restore, Maximize and Exit.
2) (This is may be related to me exiting the program with shift+f5 since I can't, for now, close my application because of the changes I mentioned).
When the application quits, after I minimzed it to the tray, the icon is left in the tray, until I pass over it with my mouse.
How can I fix it?
Just add a variable that indicates that the close was requested by the context menu. Say:
private bool CloseRequested;
private void exitToolStripMenuItem_Click(object sender, EventArgs e) {
CloseRequested = true;
this.Close();
}
protected override void OnFormClosing(FormClosingEventArgs e) {
base.OnFormClosing(e);
if (e.CloseReason == CloseReason.UserClosing && !CloseRequested) {
e.Cancel = true;
this.Hide();
}
}
Be sure to not call Close() in the FormClosing event handler, that can cause trouble when the Application class iterates the OpenForms collection. The possible reason that you are left with the ghost icon. No need to help.
I'm using a form with a OK and a Cancel button. When the user click on the Cancel button, the user will get a message to confirm if the form should close or not. A click on OK = close, but when click on Cancel, the form should not close, but thats what is happening right know, and I have tested to add some event code for the form, but still closing. What can I do to Get it to work properly?
// Button - Cancel
private void btnCancel_Click(object sender, EventArgs e)
{
// Message box to confirm or not
if (MessageBox.Show("Do you really want to cancel and discard all data?",
"Think twice!", MessageBoxButtons.YesNo, MessageBoxIcon.Question) ==
DialogResult.Yes)
{
// Yes
//this.Close(); // Closes the contact form
m_closeForm = false;
}
else
{
m_closeForm = false;
// No
// Do nothing, the user can still use the form
}
}
private void ContactForm_Formclosing(object sender, FormClosingEventArgs e)
{
if (m_closeForm)
e.Cancel = false; // Stänger formuläret. Inget skall hända
else
e.Cancel = true; // Stänger inte formuläret
}
You can try the following, by adding the messagebox with the dialog result in the form closing event. I believe this is the better approach:
private void btnCancel_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Do you really want to cancel and discard all data?", "Think twice!",
MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
{
this.Close();
}
// Form wont close if anything else is clicked
}
private void btnOk_Click(object sender, EventArgs e)
{
// PerformAction()
this.Close();
}
I think this is what you are looking for.
I think you'll find that in your form's Designer.cs file you'll have the following line:
this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
Remove this line and your form will no longer automatically close regardless of the result of your customer MessageBox.
To Cancel Closing you can use the FormClosingEventArgs Property, ie, e.Cancel to true.
Use this code in FormClosing Event of the Form.
if (MessageBox.Show("Do you really want to cancel and discard all data?",
"Think twice!", MessageBoxButtons.YesNo, MessageBoxIcon.Question) ==
DialogResult.Yes)
{
e.Cancel = false;
}
else
{
e.Cancel = true;
}
I'm trying to implement some code that asks if the user wants to exit the application I've made.
It's in c# and is a windows form application.
I've had very little sleep this week and can't seem to get my head around the onFormClosing event. Could some please give me the exact code I should use to have code executed when the user clicks on the close button (the 'x' in the top right).
Please find it in your heart to help a sleep deprived moron.
Double-click the form's FormClosed event in the events tab of the Properties window in the designer.
The FormClosing event allows you to prevent the form from closing by setting e.Cancel = true.
Well, the event is called FormClosing and is cancellable. Subscribe to it, do your stuff and let the user close their form. This event is fired if the "x" button is used or if you close the form yourself.
You can subscribe to it in the designer by highlighting the form and looking in the events tab of the properties window, as SLaks says, then double-click it. You don't need to do anything special to cope with the "x" button.
The easiest way is to activate the form in the designer and find the event FormClosing in the properties windows and then just double click the event.
Then just do the following:
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (e.CloseReason == CloseReason.UserClosing)
{
var result = MessageBox.Show("Are you sure you want to exit?", "Exit", MessageBoxButtons.YesNo);
if (result != System.Windows.Forms.DialogResult.Yes)
{
e.Cancel = true;
}
}
}
If you do not specify that the reason has to be UserClosing, it will stop windows from shutting down if you do not exit the program first which is not a good practice.
public Form1()
{
InitializeComponent();
this.FormClosing += new FormClosingEventHandler(Form1_FormClosing);
}
void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (MessageBox.Show("Are you sure that you wan't to close this app", "Question", MessageBoxButtons.OKCancel) == DialogResult.Cancel)
e.Cancel = true;
}
I hope this helps
You can add event handler manually. Example to add event handler in constructor:
public frmMain()
{
InitializeComponent();
FormClosing += frmMain_FormClosing;
}
private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
{
//your code
}
Make derive your form fromf the System.Windows.Forms.Form and put this override:
protected override void OnFormClosing(CancelEventArgs e)
{
if (bWrongClose)
{
bWrongClose = false;
e.Cancel = true; // this blocks the `Form` from closing
}
base.OnFormClosing(e);
}