You need to make use of the FormClosing event. Here is a quick example:
private bool minimize = true;
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (minimize)
{
e.Cancel = true;
this.WindowState = FormWindowState.Minimized;
}
}
The reason for the minimize bool variable is to have control of whether you are closing the Form for reals or not.
vckicks
Junior Poster in Training
58 posts since Jun 2008
Reputation Points: 11
Solved Threads: 9
Ah you mean to minimize not close.. now it makes sense.
LizR
Posting Virtuoso
1,791 posts since Aug 2008
Reputation Points: 196
Solved Threads: 190
What errors do you get? Id suggest make a new winforms app, apply the code there, and if that doesnt work, please post all the code so we can see, as well as the errors if any.. If there are no physical errors, please describe what you're seeing (or not seeing)
LizR
Posting Virtuoso
1,791 posts since Aug 2008
Reputation Points: 196
Solved Threads: 190
I thought it goes without saying, but add this in the constructor of your Form:
This.FormClosing += new EventHandler(Form1_FormClosing);
I'm not too sure about the EventHandler part, but the point is attach the event otherwise the code will do nothing.
vckicks
Junior Poster in Training
58 posts since Jun 2008
Reputation Points: 11
Solved Threads: 9
this.WindowState = FormWindowState.Minimized;
Thanks, just browsing through.. But this solved my problem as well.
Goalatio
Junior Poster in Training
72 posts since Oct 2009
Reputation Points: 10
Solved Threads: 0
I know this is solved but i felt it really needed to be said:
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
//components.Dispose();
// we've to comment the above line and added below line
this.WindowState = System.Windows.Forms.FormWindowState.Minimized;
}
//base.Dispose(disposing); //u have to comment this line
}
isnot the way to go about it. You will prevent your form and controls from being correctly marked for garbage collection which could result in memory leaks.
If you want to minimise instead of closing use the originally posted code to cancel the FormClosing event and minimise the form instead.
Ryshad
Nearly a Posting Virtuoso
1,307 posts since Aug 2009
Reputation Points: 512
Solved Threads: 246