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

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

Related

Creating new form over parent form

I'm trying to create a form over the parent form so that wherever the parent form is the new form will be created in the same place. I've looked around and have so far found this:
private void Cleaning_Click(object sender, EventArgs e)
{
this.Hide();
Form2 form2 = new Form2();
form2.Show();
form2.Location = new Point(this.Left, this.Top);
this.Close();
}
But I can't figure out how to fully close the old parent form without closing the newly created form.
Here is my old code:
private void Cleaning_Click(object sender, EventArgs e)
{
this.Hide();
Cleaning c = new Cleaning();
c.ShowDialog();
this.Close();
}
OK the main problem now is that the this.Close closes both the forms and I really need some advice.
Thanks for any help.
The form you are trying to close is the main form of the application so if you close it all other form will close with it
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Form1 form1 = new Form1();
Form1 form2 = new Form2();
Application.Run(form1);
// It will run form1 until it close then run the form2
Application.Run(form2);
}
}
}
Please try this:
private void Cleaning_Click(object sender, EventArgs e)
{
this.Hide();
Form2 form2 = new Form2();
form2.Show();
form2.Location = new Point(this.Location.X, this.Location.Y);
this.Close();
}
And change property of new form: StartPosition => Manual
Hope this help !
Use Hide property to hide the parent form after Show of child form.
Add Application.Exit() to the close button of the child form. (if you want to exit from child form)
Do not add the this.Close() in the parent form.
PS: Tell me if I missed something.

Closing Multiple Forms in C#

I have total 3 forms (Form1, Form2 and Form3) in my Windows Forms Application.
Form2 is log-in page. When user clicks on sign-in button in Form1, Form2 must be open and if user provides accurate username and password then Form3 is needed to open and to close both Form1 and Form2.
How to code such thing in C#? I am using Microsoft Visual Studio 2012.
So far I have done following procedure:
double click the Form1 to get at the coding window and wrote-
Form2 secondForm = new Form2();
Just outside of the Form Load event
& inside the button, i wrote-
secondForm.Show();
So when I run the solution, Form2 is opened by clicking a button in Form1 (Works Perfectly!). But I have no idea how to close Form1 and Form2 when user enter correct username and password combination in Form2 to open Form3.
Form1 firstForm = new Form1();
firstForm.Close();
isn't closing the form.
Please guide me.
You should add a new Class with a Main() method. (OR) There will be Program.cs in your project.
And, start the application from the Main() method. You can change "Startup object:" property of your project to "<YourApplicationName>.Program".
You Main() method should show Form1 and Form2 as Dialog.
If DialogResult is OK then run the Form3 by Application.Run() method.
DialogResult r;
r = (new Form1().ShowDialog());
if( r == DialogResult.OK )
Application.Run(new Form3());
You cannot close the main form (the one that you used to start the message loop) if you do that will end/close the entire application. What you can do however instead is this:
Form1 code
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var f2 = new Form2();
var res = f2.ShowDialog();
if (res == DialogResult.OK)
{
var f3 = new Form3();
this.Visible = false;
f3.ShowDialog();
this.Close();
}
}
}
Form2 code:
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void buttonLogin_Click(object sender, EventArgs e)
{
// if username and password is ok set the dialog result to ok
this.DialogResult = DialogResult.OK;
this.Close();
}
}

If Else Condition For .Close?

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....}

show a form at its current state instead of new form()

I have created a C# application.
Here I have two forms, form1 and form2.
form2 is called from form1.
Later form2 is made hidden.
Now I want to show form2 from form1.
Please give me some idea.
You need to keep reference to Form2 object, and when you want it to be visible, just call frm2.Show() - don't construct the new Form2 object with new Form2() - use the existing one.
// You need to contruct Form2 before calling Show().
Form2 frm2 = new Form2();
// Some handler somewhere
void btnShowForm2_Click(..., ...)
{
frm2.Show();
}
Edit: As Micah pointed out, you will want to hide Form2 instead of closing it:
private void Form2_FormClosing(object sender, FormClosingEventArgs e)
{
this.Hide();
e.Cancel = true; // this cancels the close event.
}
You will want to use form.hide() when hiding form2 instead of form.close
keep a reference to form2 and call form.show when you want to show it again
take form2 instance variable at class level
example
Public Class Form1
{
Form frm2;
//Show form here
protected void Button1_Clik
{
frm2=new Form2();
frm2.Show();
}
//Even the form is hidden, you may show the same instance /same state of form again
protected void Button2_Click()
{
frm2.Show();
}
}

Open an existing form from the main form

I designed two forms: Form1 and Form2. Form1 is the main form. There is a button in Form1, if I click the button, then Form2 will pop out. I want to do something on Form2.
// click button in Form1.
private void button1_Click(object sender, EventArgs e)
{
Form form2= new Form();
form2.ShowDialog();
}
But Form2 is a new form rather than an existing form.
It is wrong.
How? Thanks.
You are creating instance of Form class not the Form2 which you have in your project. Create instance of Form2 which you created earlier and then call ShowDialog in it.
You might have notice the in the program.cs something like Application.Run(new Form1()); Here we create the instance of Form1 and pass to Run method.
Do it this way by creating instance of Form2 and calling ShowDialog() method to show it
Form2 form2= new Form2();
form2.ShowDialog();
You create blank form with
Form Form2= new Form();
You should use
Form2 form2= new Form2();
Complete code:
private void button1_Click(object sender, EventArgs e)
{
Form2 form2= new Form2();
form2.ShowDialog();
}
Declare
Form2 form2= new Form2();
like your class member and use it like this:
private void button1_Click(object sender, EventArgs e)
{
form2.ShowDialog(); //blocking call
//or form2.Show() //non blocking call
}
EDIT
Based on correct comments, to make this work instead of executing the Close() on the function which will lead to Dispose() you need to use form2.Hide() to make is simply invisible
private void button1_Click(object sender, EventArgs e)
{
InputForm form1 = new InputForm();
form1.Show();
}
Here InputForm means which form you want to open.
The question is "Open an existing form from the main form"
Okay lets change it a little, Open an existing instance of form from the main form.
when you show a form
new Form2().Show();
lets say you hid it using
Form2.Hide();
you guys can use this
var Form2_instance = Application.OpenForms.OfType<Form2>().Single();
Form2_instance.Show();

Categories