Creating an event when a form is closed [duplicate] - c#

This question already has answers here:
Executing code when my form is closed
(3 answers)
Closed 8 years ago.
I want to create a method that when the x button that closes the application is pressed (it is in the upper right hand corner) I save all the text into a file. From my limited c# experience when I click on a button or text box a method is created, however when I click on the x it takes me to the method for when the windows form is loaded. When I did a Google search the results pointed me to if I wanted to close the application not make an event happen when the form is closed. How do I get create an event when the form is closed?

If you have the form selected in the Designer in Visual Studio, you can select the FormClosed event from the Properties window and it will automatically generate an event method for when the form is closed, which you can then add your relevant code to.

You can register to Form.FormClosing event:
Form form1 = new Form();
form1.FormClosing += (o, e) =>
{
// Do stuff you want
}

Add this code on FormLoad:
this.FormClosing += MainPage_FormClosing; // occurs before closing of the form
this.FormClosed += MainPage_FormClosed; // occurs after the closing of the form
private void MainPage_FormClosed(object sender, FormClosedEventArgs e)
{
// your code here to do something before closing the form
}
private void MainPage_FormClosing(object sender, FormClosingEventArgs e)
{
// your code here to do something after the form is closed
}
I think this is the answer to your question.

Related

C#.net : Accidental Double Click on a button shows 2 different forms [duplicate]

This question already has answers here:
The proper way to check if a form is already shown?
(2 answers)
Closed 3 years ago.
so here's my code:
private void loginbtn_Click(object sender, EventArgs e)
{
LogIn();
}
private void LogIn()
{
//some code to validate users
//if user and password is in db, show Form2 and record login event to Audit Trail table
}
I never knew this problem is possible to happen until i accidentally pressed enter twice,because i set loginbtn as AcceptButton for Form1 and suddenly, two Form2's popped up on my screen, and so I restarted my program and tried to double click the loginbtn to check the problem, and yes, two Form2's popped up again on my screen. This only happens on accidental double clicks and not when i click the button once or press the enter button once at the Form1.
Someone please tell me how to prevent it from running the action twice? how do i fix it?
Thank you so much.
A possible solution is to declare a boolean variable, IsShowing, which is true when Form2 is showing and false when it is not. Then you can write:
private void loginbtn_Click(object sender, EventArgs e)
{
if (!IsShowing)
LogIn();
}
Another solution I can think of is to set Form2 as modal. Doing like this, the second instance won't appear anymore.
A third solution would be disabling the button after Form2 is showing.

WinForms; detecting form closed from another form

Is it possible to detect a form closing from another form.
For example.
If I had a mainForm that opens subForm, can I detect within the mainForm that the subForm has closed and execute code?
I understand I could create an event handler within the subForm, but this is not really what I'm after because what I'm about to do after the subForm closes, is within the mainForm (changes to mainForm).
The FormClosed event is public, so you can create a handler from the main form.
//Inside main Form. Click button to open new form
private void button1_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
f2.FormClosed += F2_FormClosed;
f2.Show();
}
private void F2_FormClosed(object sender, FormClosedEventArgs e)
{
MessageBox.Show("Form was closed");
}
Take a look at the public FormClosedEvent. Since the modifier is public, you're able to do something like the following example:
SubForm subForm = new SubForm();
subForm.FormClosed += delegate
{
MessageBox.Show("subForm has closed");
};
subForm.ShowDialog();
The above example creates a new form (of type SubForm), adds a new event handler to display a message box telling the user that the form has closed, and finally uses the ShowDialog() method which will prevent the user accessing the main form until the sub form has been closed.
The usual case for this is a "Modal Dialog" (like Message Box and its Family).
Every form can be opened as Modal Dialog, by using ShowDialog() isntead of Show().
Otherwise the event way is the only way.

changing the control box on a form when exiting

Ok, I have a question about the Form Controlbox. I was wondering if it is possible to change or add what the exit button does on the form.
I can easily minimize, maximize and exit the form no problem. But this is what I am facing.
My app has an access login. After you log in it comes to the main form. I have a log out button when pressed, it goes back to the login form.
However, if you press the exit button, it exits the main form, and the program is still running, but with no way to bring the login form up.
So what I am trying to do is, when the main form is exited through the red X I want it to go to the login.
I can go the complex route: borderless form, movable form, custom buttons and etc., etc.,
I think it would be easier to change or add the exit button to return to the login form. Is this possible?
Move the logic out of your button click event, into a separate method.
private void button1_Click(object sender, EventArgs e)
{
OverrideFormExit();
}
private void OverrideFormExit()
{
// execute the code that was previously in button1's click event
}
Now you can subscribe that same method to your Form's Closed event, so that it executes when the user closes the Form.
For example, place the following in your Form's constructor:
FormClosed += (s, e) => OverrideFormExit();
Alternatively, you can subscribe to the main Form's Closed event from within the Login Form, when you instantiate the main Form. I'm guessing at what your code looks like here, obviously.
private void ShowMainForm()
{
FormMain frmMain = new FormMain();
frmMain.Show();
frmMain.FormClosed += (s, e) => this.Show();
this.Hide();
}

Multiple UIs in a Windows Forms program

I have a window forms project, I have a login screen, a menu and a couple of other forms, I'm switching between them with:
this.Hide();
frm.FormClosed += new FormClosedEventHandler(subFormClosed);
frm.Show();
and the FormClosedEventHandler(subFormClosed);
private void subFormClosed(object sender, FormClosedEventArgs e)
{
this.Close();
}
So the aim of this is that when a subform is closed by the user to close this.
There is however a problem, I want to go back to the menu and the issue is that I have one of two possibilites, that I can see:
I can pass the menu form to the subForm by reference to then show it and hide the subform - this seems to be one really really kludgy way of doing it but it would work.
I can just open a new version of the menu form - this would lead to huge memory issues in overuse (more instances being created and then never destroyed until the program is closed, e.g. 30 menu forms sub forms)
I was trying to use the CloseReason to check if the sub form was closed by the user or if it was closed from code, however both the exit button and this.Close() return CloseReason.UserClosing. Hence I couldn't differentate between the two types of exiting.
So basically what I'm asking for is there a better way of doing this, I've read about MDI and SDI and I can't really work out which would be applicable, or if the kludgy option 1 is the best way of doing this.
You can use ShowDialog and pass the menu page as the Owner. Something like this:
In Menu:
// on menu navigation button click
this.hide();
SubForm sub = new SubForm();
sub.ShowDialog(this); // open as a dialog with this form as the owner
In Sub Form:
// on subform's back button click or better, in the FormClosing event
this.Owner.show();
this.Close(); // this line is not needed if implemented in FormClosing event
Although the answer with the ShowDialog solution is a very good one, here is another way to do if for whatever reasons one does not want to use ShowDialog:
In the constructor of your menu form, use the FormClosed and the Shown events of your subforms this way:
subForm1.FormClosed += (s, e) => showMenu();
subForm1.Shown+= (s, e) => hideMenu();
subForm2.FormClosed += (s, e) => showMenu();
subForm2.Shown+= (s, e) => hideMenu();
...
void showMenu()
{
this.Show();
}
void hideMenu()
{
this.Hide();
}
Then you can use subForm1.Show() freely and close them the way you want: the events will be triggered accordingly.

How to detect when owner form is closed from an inner control?

How to detect when owner form closes (from a control inside it)?
UPD I need the control to know that it's form is closing, not vice versa
Credits to Fredrik Mörk for this solution:
FindForm().FormClosing += parentForm_FormClosing;
You should intercept FormClosing event. In FormClosingEventArgs the variable CloseReason will show you why is the form closing. Your best bet is intercepting when this variable equals UserClosing enumerated value.
The form owner closing is when a form is closed by another parent form that can close the form or the form is closed when the parent form is closed.
Use the form closing event to check if another form closed the form:
private void AppMainForm_FormClosing(object sender, FormClosingEventArgs e)
{
if(e.CloseReason == CloseReason.FormOwnerClosing)
{
// do something
}
else
{
// do nothing
}
}

Categories