If Else Condition For .Close? - c#

i got 2 forms 1mdiparent, 1child
lets say mdiparent = Form1 then child = Form2 .
i got New button in Form1 calling childform (Form2) like:
private void newDocument_ItemClick(object sender, ClickEventArgs e)
{
Form2 formChild = new Form2();
Form2.Show()
}
now my question was whats the if else condition for : if Form2 == Close?
something like:
if (Form2.Close == true){ //condition }
or if (Form2 == Close){ //condition }
but i know its not the right code .so hope you could help me :) thanks .

If I understand your question correctly, you want to be notified by the system when the Form2 is closed so you could apply some internal logic to avoid the reopening of the child form and apply some kind of changes to your main interface.
If this is your problem then you could add your event handler for the FormClosing event of the Form2 directly in the code of Form1 when you open the Form2
// Flag to keep the state open/close of the child form
private bool childClosed = true;
private void newDocument_ItemClick(object sender, ClickEventArgs e)
{
if(childClosed == true)
{
Form2 formChild = new Form2();
// Setup the event handler form the Form2 closing directly here in the MDI
formChild.FormClosing += new FormClosingEventHandler(myFormClosing);
formChild.Show();
// set the flag to avoid the reopening
childClosed = false;
}
}
// Now, when the formChild closes, you will receive the event directly here in the MDI
private void myFormClosing(object sender, FormClosingEventArgs e)
{
// The child form is closing......
// Do your update here, but first check the close reason
if(e.CloseReason == CloseReason.UserClosing)
{
......
// reset the flag so you could reopen the child if needed
childClosed = true;
}
}

You will probably want to use either the Form.FormClosed event or the Form.FormClosing event. Probably the former since you don't really want to interact with the closing of the form.
You would create a method and have it called when the event is fired and this would do whatever you wanted (such as hide buttons and such like).
See http://msdn.microsoft.com/en-us/library/system.windows.forms.form.formclosed.aspx for details of the formclosed event.

When a form is closed, it's disposed too. Thus just check if it's disposed by following code:
Form2 formChild = new Form2();
// ...
if (formChild.IsDisposed) {
// Do someting
}

As #V4Vendetta pointed out: there is a FormClosing event (called before the form has closed. Used to tell the user "You haven't saved yet") and a FormClosed event (called after the form closed).
public class Form2 : Form
{
public bool hasClosed;
private void Form2_FormClosed(object sender, FormClosedEventArgs e)
{
hasClosed = true;
}
}
with this, you can do
if (formChild.hasClosed)
// do something

It is wrong to take this approach, the Form 2 is initialized in the button click event, therefore, you assume that the form object was not available.
if you want to change this order, then the form should be initialized somewhere else like the constructor of the Form 1.
private Form2 form2;
public Form1()
{
form2 = new Form2();
}
private void newDocument_ItemClick(object sender, ClickEventArgs e)
{
if(!form2.Visible)
{
form2.Show();
}else
{
form2.Hide();
}
}
Hiding a form is not same as closing a form, if you really open and close the form2 and carry out some action based on that, then you should set a property on the parent form when the form2 closing event is triggered, to do this you must pass the parent form as an argument in the form2 constructor.

You can check that with the help of the following code
foreach (Form f in Application.OpenForms)
{
if (f.Text == formName)
{
IsOpen = true;
break;
}
}
if(!IsOpen)
{....do your code....}

Related

Use Form.Show() but Not running code After Form.Show() Like ShowDialog()

I can't use Form.ShowDialog() I want use Form.Show() but I want execute code after From.Show() after Form.Closed
public void Tools(){
var frm=new ToolFrm();
frm.Show();
//do something
}
I want return true and hold execution while the form frm is open.
If you want to run some code when a modeless form is closed, then you can subscribe to to the form's FormClosed event:
public bool Tools()
{
var frm = new ToolFrm();
frm.FormClosed += Form_FormClosed;
frm.Show();
return true;
}
private static void Form_FormClosed(object sender, FormClosedEventArgs e)
{
((Form)sender).FormClosed -= Form_FormClosed;
MessageBox.Show("Form was closed");
}
Note that if you don't unsubscribe from the FormClosed event, then the subscribing object will keep alive a reference to the form until the subscribing object is garbage collected.
To prevent that behaviour, you can unsubscribe from the event in the handler, as I have done with the line:
((Form)sender).FormClosed -= Form_FormClosed;
If I understand your question correctly, you want to run code when the form is re-opened. The showdialog is actually a option you want and need to use.
private bool Tools()
{
this.Hide();
using (Form frm = new ToolFrm())
frm.ShowDialog();
DoSomethingYouWant(); //For example return true/false;
this.Show();
}
In the method DoSomethingYouWant() you can do anything you want to do.
The form will be hidden while the user untill the ToolFrm is closed.
If you want to run of example a new FormLoad() event, you can subscribe to it.
By replaceing the DoSomethingYouWant() with FormName_Load(this, e);
In the loading event you could do :
private void Form1_Load(object sender, EventArgs e)
{
if(Tools){
Messagebox.Show("true")
}
if(!Tools{
Messagebox.Show("false")
}
}

How to instantly call action in Form1 on closing Form2

So basically i have Form1
From Form1 I can open Form2 with this code:
private void btn_Komplexity_Click(object sender, EventArgs e)
{
Form2 kompleksaForma = new Form2();
kompleksaForma.ShowDialog();
}
When Form2 is opened there is something and at the end there is this.Close();
After this.Close(); (closing Form2) is it possible to call instant action on Form1?
If you're sticking to ShowDialog(), this function will block until the form is closed.
private void btn_Komplexity_Click(object sender, EventArgs e)
{
using (Form2 kompleksaForma = new Form2())
{
kompleksaForma.ShowDialog();
PutStuffHereAfterClose(); // (or outside the using block if it doesn't need
// to access properties of kompleksaForma)
}
}
If you're showing Form2 as a modal window using form2.ShowDialog() or form2.ShowDialog(this), then...
form2.ShowDialog(this);
if (form2.DialogResult == DialogResult.OK)
{
CallOtherStuffHere();
}
... as the ShowDialog() method will block execution until the closure of Form2, then continue.
I'm using DialogResult above to test for validity, but you could implement some other method, if you wish.
If you're showing Form2 as a non modal window, then you should pass a reference of Form1 to Form2 first. This could be done in its constructor...
var form2 = new Form2(form1);
Or, you can pass it in the Show() method, to set form1 as its parent...
var form2 = new Form2();
form2.Show(form1);
Then, you can access the parent form via form2.Parent. However, you may have to cast it to a Form1 instance before you call your methods explicitly. And this can be done in the Closing event handler of Form2.
Further info here regarding modal and modeless windows:
https://msdn.microsoft.com/en-us/library/aa984358(v=vs.71).aspx
There are some events triggered after the window is closed. You can subscribe to them and add your code to the handler method:
Form2 kompleksaForma = new Form2();
kompleksaForma.FormClosing += KompleksaForma_FormClosing;
kompleksaForma.FormClosed += KompleksaForma_FormClosed;
kompleksaForma.Deactivate += KompleksaForma_Deactivate;
kompleksaForma.ShowDialog();
And then implement one of the handlers like that:
private void KompleksaForma_FormClosing(object sender, FormClosingEventArgs e)
{
// Your code here
}
private void KompleksaForma_FormClosed(object sender, FormClosedEventArgs e)
{
// or here
}
private void KompleksaForma_Deactivate(object sender, EventArgs e)
{
// or here
}
First will trigger FormClosing, then FormClosed. Last one is Deactivate.

Switching between forms and sending variable correctly

I am wondering how can I correctly switch between forms by button click event.
I have Form1 and Form2.
Form1 have: -TextBoxForm1
-ButtonForm1
Form2 have: -TextBoxForm2
-ButtonForm2
I would like to on_click ButtonForm1 event go to the Form2. Then I want to write some message to TextBoxForm2 and press ButtonForm2 it will go to the Form1 again and message from TextBoxForm2 will appear in TextBoxForm1.
Everything works fine, but I have one problem. When I close application and I wanna debug and start it again, some errors appear like:"application is already running".
Form1:
public static string MSG;
public Form1()
{
InitializeComponent();
TextBoxForm1.Text = MSG;
}
private void ButtonForm1_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2();
this.Hide();
//There is probably my fault but when I was trying this.Close(); everything shutted down
form2.Show();
}
Form2:
private void ButtonForm2_Click(object sender, EventArgs e)
{
Form1.MSG = TextBoxForm2.Text;
Form1 form= new Form1();
form.Show();
this.Close();
}
How can I do this correctly please? :) I am beginner, thank you!
I would not go the route of using a STATIC for passing between forms as you mention you are a beginner, but lets get the closing to work for you.
In your main form create a new method to handle an event call as Hans mentioned in the comment. Then, once you create your second form, attach to its closing event to force form 1 to just become visible again.
// Inside your Form1's class..
void ReShowThisForm( object sender, CancelEventArgs e)
{
// since this will be done AFTER the 2nd form's click event, we can pull it
// into your form1's still active textbox control without recreating the form
TextBoxForm1.Text = MSG;
this.Show();
}
and where you are creating form2
private void ButtonForm1_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2();
form2.Closing += ReShowThisForm;
this.Hide();
form2.Show();
}
and in your second form click, you should only need to set the static field and close the form
private void ButtonForm2_Click(object sender, EventArgs e)
{
Form1.MSG = TextBoxForm2.Text;
this.Close();
}
Easy solution is to use modal form. Display Form2 temporarily, when it is displayed Form1 is invisible.
var form2 = new Form2();
this.Visible = false; // or Hide();
form2.ShowDialog(this);
this.Visible = true;
And to pass data you can define property in Form2, to example:
public string SomeData {get; set;}
Form1 has to set SomeData, which you take in Shown and display. Same property can be used to get data from Form2 (before closing).
// form 1 click
var form2 = new Form2() { SomeData = TextBoxForm1.Text; }
this.Visible = false;
form2.ShowDialog(this);
this.Visible = true;
TextBoxForm1.Text = form2.SomeData;
// form 2 shown
TextBoxForm2.Text = SomeData;
// form 2 click
SomeData = TextBoxForm2.Text;
Close();

Closing multiple windows form with single click

I want to close two forms at the same time. I have one main form that starts with program. when user click button, the main form will hide and other form will pop up. on the second form if user click "back to main " button, it should hide second form and show main form. But the problem is if user tries to close the second form it should close the main form as well. How can i close the main form as well
I would just use the Application.Exit() for what is requested by this thread.
Application.Exit();
UPDATE: corrected
I had said this will not call the form closing events but in documentation it does actually call it here is a link to the documentation
http://msdn.microsoft.com/en-us/library/ms157894(v=vs.110).aspx
It was better if you specified what codes you wrote for going back to main form, so I could help you by changing your codes. But now because I don't know how you did it, I have to write codes for both of those tasks.
It can be possible using a Boolean variable to do what you want. Follow bellow codes:
public partial class MainForm : Form
{
//"Click" event of the button that should opens the second form:
private void goToSecondForm_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2(); //Or you can write it out of this method.
this.Hide(); //Hides the main form.
f2.ShowDialog(); // Shows the second form.
this.Show(); // Shows the main form again, after closing the second form using your own button.
}
}
public partial class Form2 : Form
{
bool selfClose = false; //False shows that user closed the second form by default button and true shows that user closed it by your own button.
//"Click" event of the button that should closes just the second form and returns user to the main form:
private void ownCloseButton_Click(object sender, EventArgs e)
{
selfClose = true; //Means user clicked on your own button.
this.Close(); //So the program closes the second form and runs f2_FormClosed method, but because selfClose became true here, happened nothing there and program will go back to goToSecondForm_Click method in the main form and will run this.Show() .
}
//"FormClosed" event of the second form :
//Whether user clicked on your own button or on the default one, this method will run.
private void f2_FormClosed(object sender, FormClosedEventArgs e)
{
if (!selfClose) //It means user didn't click on your own button and both of forms must be closed .
Application.Exit(); //So the program closes all of forms (actually closes the program) and couldn't access to any other commands (including this.Show() in goToSecondForm_Click method).
}
}
As others have said, you need to somehow call .Close() on the main form when your child form is closed. However, as you've pointed out, you don't have a reference to the main form automatically in your child form! That leaves you with a few options.
1. Exit the application immediately.
This is done by calling Application.Exit(); in your child form's "back to main" button's click event handler. It will immediately close all forms, which might simply be what you want.
// .. ChildForm code ..
void OnBackToMainClicked(object sender, EventArgs e)
{
Application.Exit();
}
2. Pass a reference to the main form to the child form.
This is probably the most common way to solve this problem in general. When you create your child form in your main form, you'll need to pass a reference as follows:
// .. MainForm code ..
void OnGoToChildForm(object sender, EventArgs e)
{
var childForm = new ChildForm(this);
childForm.Show();
}
// .. ChildForm code ..
private MainForm mainForm; // This is where the child form will keep a reference to
// the main form that you can use later
public ChildForm(MainForm mainForm)
{
// This is the child form's constructor that we called above,
// and it's where we'll save the reference to the main form
this.mainForm = mainForm;
}
// This also needs to be the event handler for the close event
void OnBackToMainClicked(object sender, EventArgs e)
{
this.Close();
mainForm.Close();
}
3. Add an event handler on the child form's FormClosed event. This is a safe way to solve the problem if you are concerned about keeping your main application logic under the control of the main form. It's similar to the solution suggested by Lamloumi above, but it's all done in the main form's code.
// .. MainForm code ..
void OnGoToChildForm(object sender, EventArgs e)
{
var childForm = new ChildForm(this);
childForm.FormClosed += new FormClosedEventHandler(SecondForm_FormClosed);
childForm.Show();
}
void SecondForm_FormClosed(object sender, EventArgs e)
{
// Perform any final cleanup logic here.
this.Close();
}
Form1 _FirstForm = New Form1();
Form2 _SecondForm = New Form2();
MainForm _MainForm = new MainForm();
_FirstForm.Close();
_SecondForm.Close();
_MainForm.Show();
Normally , in the Home form you have some ting like this :
SecondForm second= new SecondForm ();
second.Show();
this.Hide();
In the SecondForm you must ovveride the event of closure like this :
public class SecondForm :Form{
public SecondForm()
{
InitializeComponent();
this.FormClosed += new FormClosedEventHandler(SecondForm_FormClosed);
}
void SecondForm_FormClosed(object sender, FormClosedEventArgs e)
{
Application.Exit();
}
}
To be sure that your application is closed after you close the form. because the Home from is still active and hidden if you don't.
use this in Form2
private void button1_Click(object sender, EventArgs e)
{
Form1.FromHandle(this.Handle);
}
There Handle are the same now ;
hope this work.

C#, how to hide one form and show another?

When my project starts Form1 loads and checks the program license with the server, if everything's OK it should: show Form2 and close Form1. Afterward when the user would close Form2 with the "x", the program should end.
What do you think would be the best way of doing it?
So far got only to form2.Show :)
...
if (responseFromServer == "OK")
{
Form2 form2 = new Form2();
form2.Show();
}
Thanks!
I use something like this. Code is in Program.cs
public static bool IsLogged = false;
Application.Run(new FUserLogin());
if (!isLogged)
Application.Exit();
else
Application.Run(new FMain());
As you probably know if you use Form1 as your main form then you can't close it as this will close the application (unless you customize the way the app starts, but that's more advanced).
One option is to start by creating Form2 as your main form, but keep it hidden, then create and show Form1, and then when the license check is finished, close Form1 and make Form2 visible.
Or you can start by showing Form1 and then when the license check is done, call Form1.Hide() and then create and show Form2. Then when Form2 is closed by the user, call Form1.Close() in the Form2.Closed event handler:
class Form1
{
private void Form1_Load(object sender, EventArgs e)
{
// do the license check,
// and then when the license check is done:
if (responseFromServer == "OK")
{
Form2 form2 = new Form2();
Form2.FormClosed += new FormClosedEventHandler(Form2_FormClosed);
Form2.Show();
this.Hide();
}
else
this.Close();
}
private void Form2_FormClosed(object sender, FormClosedEventArgs e)
{
this.Close(); // will exit the application
}
}
You can show the first form using ShowDialog, which will block until the form closes. Inside Form1 you can just call this.Close() when it is done processing, and either set the DialogResult property, or (probably cleaner) you can create a public property that Form1 sets before it closes, and have the caller check that. Then you can either return from Main directly, or go ahead and instantiate your new class and pass it to Application.Run().
static class Program
{
[STAThread]
static void Main()
{
var form1 = new Form1();
var result = from1.ShowDialog(); // Form1 can set DialogResult, or another property to indicate success
if (result != DialogResult.OK) return; // either this
if (!form1.ValidationSuccessful) return; // or this
Application.Run(new Form2());
}
}
I like this because you are not referencing Form2 from Form1, all of the code to deal with showing Form1 and exiting the application is consolidated in one place, and can easily be commented out for development or testing.
Try this to hide Form1:
this.Hide();
then in your FormClosing event of Form2:
Form2_FormClosing(object sender, EventArgs e)
{
Application.Exit();
}
Try this
//Form1 code
if (responseFromServer == "OK")
{
this.Hide();
Form2 frm = new Form2();
frm.Show();
}
And you can exit from the application using Application.Exit() method in the Form2's form closing event
//Login Form Load Events or Constructor
this.Close(); //first Close Login From
Application.Run(new Main());//second Run Main Form

Categories