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();
}
}
Related
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.
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();
I have two forms. I need to open a second form with a button. When I open form2 I hide form1. However when I try to show form1 again from form2 with a button it doesn't work. My form1 code is:
Form2 form2 = new Form2();
form2.ShowDialog();
Inside form2 code:
Form1.ActiveForm.ShowDialog();
or
Form1.ActiveForm.Show();
or
form1.show(); (form1 doesn't exist in the current context)
doesn't work.
I do not want to open a new form
Form1 form1 = new Form1();
form1.ShowDialog();
I want show the form which I hided before.
Alternatively I can minimize it to taskbar
this.WindowState = FormWindowState.Minimized;
and maximize it from form2 again.
Form2.ActiveForm.WindowState = FormWindowState.Maximized;
however the way I am trying is again doesn't work.
What is wrong with these ways?
You could try (on Form1 button click)
Hide();
Form2 form2 = new Form2();
form2.ShowDialog();
form2 = null;
Show();
or (it should work)
Hide();
using (Form2 form2 = new Form2())
form2.ShowDialog();
Show();
Preserve the instance of Form1 and use it to Show or Hide.
You can access Form1 from Form2 throught the Owner property if you show form2 like this:
form2.ShowDialog( form1 )
or like this:
form2.Show( form1 )
Notice this way you are not forced to use ShowDialog cause hide and show logic can be moved inside Form2
This method is the one that I find works the best for me
Primary Form
Form2 form2 = new Form2(this);
Secondary Form
private Form Form1
public Form2(Form Form1)
{
InitializeComponent();
this.Form1 = Form1;
Form1.Hide();
}
Later on when closing
private void btnClose_Click(object sender, EventArgs e)
{
Form1.Show();
this.Close();
}
FormCollection frm = Application.OpenForms;
foreach(Form f in frm)
{
if(f.Name=="yourformname")
{
f.Show();
this.Close();
this.Dispose();
return;
}
}
I'm trying to solve this problem for a long time.
I have 2 forms, my objectives are:
When user minimize form2, form1 must minimize too.
When user maximize form2, form1 must maximize too.
When both forms are obscured by another window, and user clicks in the form2 icon in taskbar, form1 must also come to front.
The first 2 things I solved with the a_Resize method. But I can't do the third one. I tried with activate event but when I do that the form2 keeps blocked.
Here is my code:
public partial class Form1 : Form
{
Form2 form2;
public Form1()
{
InitializeComponent();
form2 = new Form2();
form2.Show();
form2.Resize += new EventHandler(a_Resize);
}
void a_Resize(object sender, EventArgs e)
{
if (((Form)sender).WindowState == FormWindowState.Minimized)
{
this.WindowState = FormWindowState.Minimized;
}
else
{
this.WindowState = FormWindowState.Normal;
}
}
}
If I add a handler to the form2 activate event:
form2.Activated += new EventHandler(form2_Activated);
And call for instance the Focus method (I tried other methods too), the form2 keeps blocked behind form1.
void form2_Activated(object sender, EventArgs e)
{
this.Focus();
}
Someone have any ideas how I can do that?
When you create form2, just pass this as a parameter to Show() to signify that form1 is the owner. With an owner link, the forms will always be raised together (at least in my experience -- I don't have a specification to back me up on this).
public Form1()
{
InitializeComponent();
form2 = new Form2();
form2.Show(this); //pass 'this' as argument to Show() to link them
form2.Resize += new EventHandler(a_Resize);
}
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