How to show form after it was closed? - c#

I have a MDI application with couple of windows. Is there any way to disable disposing form after it was closed by the user. I want to be able to reopen that form just by calling form.Show() method.

You could use Form.FormClosing Event.
The FormClosing event occurs as the form is being closed. When a form is closed, it is disposed, releasing all resources associated with the form.
If you cancel this event, the form remains opened. To cancel the closure of a form, set the Cancel property of the FormClosingEventArgs passed to your event handler to true.
This should do the same thing as you'd do with Form.Show()

You can save the values of the Form into a separate class before you call the Close() method of the form and load a new form which takes it's values from the saved class.

send the main form as a parameter to the child form, then the child form can reference the main form t any time
public Form MainForm = null;
public Sample(ref Form mainForm)
{
InitializeComponent();
MainForm = mainForm;
}
private void Sample_FormClosed(object sender, FormClosedEventArgs e)
{
MainForm.Show();
}

Related

Detect CloseEvent through different forms

PROBLEM SOLVED
SHORT STORY
I want to detect "FormClosing()" event through different forms, ie, when form1 is closed that is instantiated within form2, can form2 detect when user presses exit in form1?
LONG STORY
My team and I are working on a windows form application. Project has two forms: one is the main form page and the other is accessed via this main form. Main form looks like this:
And the second one looks like this:
If you press "Ekle/Sil" buttons within the main form, you are directed to form 2 where you can edit database entries. When you press "Sayfayı Yenile" button in the main form, the content of the text areas are refreshed by re-fetching entries from the database.
My problem is, I want to automatically refresh the main form when the user closes the second form. My research suggests I should use an "FormClosing()" event to detect a closing form. However, I want to detect this from the main form. Instantiating main form in second form's source code doesn't seem to be a reliable solution. Anyone can tell me how to do this?
EDIT
I solved the problem:
1) Created a public method within the main form that refreshes the page.
2) Send "this" property from the main form when creating the second form.
3) Added an "FormClosed()" handler within the second form that invokes this public method.
Still, I'm looking for a better solution.
EDIT 2
Better solution InBetween's answer
Simply use the Form.Closed event of the new child windows form. Everything is handled from the main form:
void EkleSil_Clicked(object sender, EventArgs e) //or whatever method is called when button is clicked
{
var newChildForm = new ChildForm();
newChildForm.Closed += childFormClosed;
newChildForm.Show();
}
void childFormClosed(object sender, EventArgs e)
{
((Form)sender).Closed -=childFormClosed;
updateShownData();
}
You can create a event in the second form and raise it when the form is closing .
Handle the event in the main form and refresh the main form when the event is raised
Another option would be to pass Form1 as an argument to Form2. Then use the Form.Closing event in Form2 and use the Form1 reference to trigger something.
Form1 form1Ref;
public Form2(Form1 mainform)
{
form1Ref = mainform;
}
private void Form2_FormClosing(object sender, FormClosingEventArgs e)
{
form1Ref.SomeMethod();
}

FormClosing with CloseReason = UserClosing doesn't work expectedly?

I have a main form, in the class of this form, I declare another form. This form lives with the main form until the main form is unloaded. There is a button on the main form, clicking this button will show the member form (I mentioned above). I want to prevent the member form from closing when user closes that form and I added the following FormClosing event handler for that form:
private void MemberForm_FormClosing(object sender, FormClosingEventArgs e) {
if(e.CloseReason == CloseReason.UserClosing){
e.Cancel = true;
Hide();
}
}
That works OK for that form. However if user closes the main form, this form is not closed, and it's hidden somewhere making my application seem to run silently. I want this form also to be closed. This is very simple by adding some FormClosed event handler for my main form to close the member form manually. Closing it manually is OK, but why do I have to do that? It seems that when user closes the main form, the FormClosing event of the member form is fired with a parameter FormClosingEventArgs passed in and the CloseReason is the same as the CloseReason of the main form (which is UserClosing). I don't understand this, I thought the CloseReason of the form is UserClosing only when user clicks on the X button, I thought the CloseReason for my member form is something like "MainFormClosing".
Is there some way to close the member form automatically as by default?
UPDATE
Here is the method showing the member form (showing it as a dialog):
private void ShowMemberForm_Click(object sender, EventArgs e){
memberForm.ShowDialog();
}
But I don't think this matters, because when I load my main form, even I don't need to click on the ShowMemberForm button, and try closing my main form first, it doesn't still close the member form.
Thanks!
UPDATE
There is something strange here, I've tried commenting out the line e.Cancel = true, or even all the FormClosing event handler and the problem is still there. This is so strange, it works OK before, I've just added the member form and this form relates to some Thread handling, but the thread starts only when a button on the member form is clicked. I didn't click that button.
What I have done in the past is set a flag when programatically closing
so in the MemberForm
private bool _ForceClose = false;
public void ForceClose()
{
_ForceClose = true;
this.Close();
}
private void MemberForm_FormClosing(object sender, FormClosingEventArgs e)
{
if(!_ForceClose)
{
e.Cancel = true;
Hide();
}
}
Then in your MainForm you can call
memberForm.ForceClose();
From within your MainForms FormClosing method or from your MainForms Dispose() or Deconstructor.
It's low tech, but it works. Im not sure if you should put _ForceClose = true in your MemberForm's Dispose method, i'm fairly certain when it gets there its already been closed BUT it couldn't really hurt.

How to make c# don't call destructor of a instance

I have two forms and form1 needs to get data from form2, i use a parameter in form2 constructor to gets form1's instance like this:
public form2(Form form1) {
this.f = form1;
}
and in form1:
Form form2 = new Form(this);
But it seem form1 destruct was called when i closed form1. my question is how can i avoid this problem?
EDIT: I have many typing mistakes in my question, i'm so sorry, fixed:
I have two forms and form2 needs to get data from form1, i use a parameter in form1 constructor to gets form1's instance like this:
private Form f;
public form2(Form form1) {
this.f = form1;
}
and in form1:
Form form2 = new Form(this);
But it seem form1 destructor was called when i closed form2. my question is how can i avoid this problem?
from MSDN:
When a form is closed, all resources created within the object are
closed and the form is disposed. You can prevent the closing of a form
at run time by handling the Closing event and setting the Cancel
property of the CancelEventArgs passed as a parameter to your event
handler.
As such, to prevent disposal of the resources, the only thing you can do is hide the form instead of closing it:
bool reallyClose;
protected override void OnClosing(CancelEventArgs e)
{
if (!reallyClose)
{
e.Cancel = true;
Hide();
}
base.OnClosing(e);
}
This will prevent the form being closed unless you manually set the reallyClose flag to true before closing the form.
You should make sure to close the form properly after you've finished using it.
Another option might be to decouple the data you need to retrieve from Form1 from the form itself.
In this case, form 1 cannot be destroyed until form2 is also closed. As long as form2 has a reference to form1, form1 will continue to exist. More likely, you are concerned with form1 being disposed. When form1 is closed, it will dispose itself. The object will still exist, but it will have released all its child controls and system objects such as window handles and drawing objects. Once a form has been disposed, it cannot be shown again, and all of it's controls will be inaccessible. If you try to use any of the visual components of a disposed form, it will throw an ObjectDisposedException. If you want to stop the form from being disposed, simply hide it rather than closing it. However, you should close it later once Form2 no longer needs it, otherwise it will stay around eating up memory and resources.
You should really factor whatever data you need out of both forms altogether, thereby avoiding the problem of coupled form constructors in the first place.

Do something when form is closed

how do I check if a form is closed?
I want to reload a listview's items when I close another form.
What I'm doing is:
Form1 = form with ListView
Form2 = form with TextBoxes
Opening a new form.
Creating a new folder via a textbox.
When I press "Add" in Form2 I want to reload the "ListView" on Form1.
So how am I supposed to do this?
And sorry for my bad English :(.
The simplest answer is to make a public method on Form1, let's call it RefreshList() and in your button click event on Form2, you simply call Form1.RefreshList. Here's a quick sample:
Form 2:
public Form1 ParentForm { get; set; }
private void Button_Click(object Sender, EventArgs args) {
{
// After the rest of your handler
if(ParentForm != null)
ParentForm.RefreshList();
Close(); // Close Form2 here, we're done!
}
Form 1:
private void ShowForm2()
{
Form2 form2 = new Form2();
form2.ParentForm = this;
form2.Show();
}
public void RefreshList()
{
// do your refresh here
}
Initially you mention that you want to do this when Form2 closes, but then later you mention that you want to do it "When I press "Add" in Form2 I want to reload the "ListView" on Form1." As others have mentioned, you can use the Closed event, so I took this approach to address your second case.
In Form1, you can subscribe to From2's FormClosed event.
You can handle the form Closing event as the Closed Event is obsolete if you are using anything above dot net 1.1
You can handle the FormClosed event if you simply want to react to when a particular form is closed. If you want to take it a step further, there is a FormClosing event that you could also handle and even prevent the form from closing if need to.
Having Form1 add an event handler to Form2's FormClosing event is an excellent option. However, there is an even simpler solution if Form2 is a dialog window. In other words, if it's OK for Form1 to be effectively locked and disabled while Form2 is displayed, you can simply show Form2 as a dialog window. Dialog windows show synchronously, so you can simply update the list immediately after showing Form2 and it won't hit that list-updating code until after Form2 is closed. For instance:
form2.ShowDialog(this);
updateList();

Updating textbox on mainform with a variable on a child form that is launched from main form

I have a windows form app. The main form has a textbox, and a button to launch another form. When the other form is launched, both forms are on screen (but the launched form is modal). The child form has a textbox and button, and when the button is pressed, I want the textbox on the main form (the parent) to be updated with the value in the textbox on the child form.
How is this functionality achieved?
Ideally you want to keep both forms from being dependent on each other, this could be achieved with interfaces:
public interface IMainView
{
public void UpdateValue(string val);
}
public interface IChildView
{
public void Show(IMainView parent);
}
have your main form implement IMainView and the child implement IChildView, the parent calls child.show(this) and the child calls parent.UpdateValue(blah);
Hope this helps.
If the child form is closed when the button is clicked, you could put a public property which wraps the value of the textbox on the child form. Then the main form can read this property after calling ShowDialog.
If you want this to happen without closing the child form, you can create a function on the main form to change the textbox. Then the child form would call that function.
The best ways to achive this situation are clockWize's and Hans Passants's advices.
But what about that?
Write a property for your textbox at parent form, like this.
public string TextBoxText
{
get { return txtTextBox.Text;}
set { txtTextBox.Text = value;}
}
When you are opening the child form set the owner.
ChildForm f = new ChildForm();
f.Owner = this;
f.Show();
Create an event handler to child forms button click event.
public Button1_Click(object sender; EventArgs e)
{
ParentForm f = (ParentForm)this.Owner;
f.TextBoxText = txtChildTextBox.Text;
}
i didn't compile code; so may have errors :)
}
When a button is pressed to close the launched form, returning you to the main form- the launched form's text box is still in scope.
Closing a form is merely changing the object's state, not disposing of it. So in the button eventhandler that launches the form from the main form, the next line after launching your modal window, it can access the text from the object it launched as the textbox is a child of that form's object. Unless you're launching your modal window in another thread, which I wouldn't figure you are since it's modal, when it is closed, it should go to the next line in the buttons eventhandler that launched it.
your main form may have code something like this right now (haven't done winforms in a while so bear with me if I miss something):
public void Button1_Click(object sender, ClickEventArgs e)
{
SomeFormIWantToLaunch launchForm = new SomeFormIWantToLaunch();
launchForm.ShowDialog(this);
}
You need to just add after launchForm.ShowDialog(this); something like:
this.SomeTextBox.Text = launchForm.ATextBox.Text;

Categories

Resources