I have two forms in my project (Login and Main).
What I'm trying to accoomplish is, if the login is successful, I must show the Main form and close the Login form.
I have this method in Login form that closes the Login form when the login is successful. But the Main form doesn't show.
public void ShowMain()
{
if(auth()) // a method that returns true when the user exists.
{
var main = new Main();
main.Show();
this.Close();
}
else
{
MessageBox.Show("Invalid login details.");
}
}
I tried hiding the Login form if the login process is successful. But it bothers me because I know while my program is running the login form is still there too, it should be closed right?
What should be the right approach for this?
Thanks...
The reason your main form isn't showing is because once you close the login form, your application's message pump is shut down, which causes the entire application to exit. The Windows message loop is tied to the login form because that's the one you have set as the startup form in your project properties. Look in your "Program.cs" file, and you'll see the responsible bit of code: Application.Run(new LoginForm()). Check out the documentation for that method here on MSDN, which explains this in greater detail.
The best solution is to move the code out of your login form into the "Program.cs" file. When your program first starts, you'll create and show the login form as a modal dialog (which runs on a separate message loop and blocks execution of the rest of your code until it closes). When the login dialog closes, you'll check its DialogResult property to see if the login was successful. If it was, you can start the main form using Application.Run (thus creating the main message loop); otherwise, you can exit the application without showing any form at all. Something like this:
static void Main()
{
LoginForm fLogin = new LoginForm();
if (fLogin.ShowDialog() == DialogResult.OK)
{
Application.Run(new MainForm());
}
else
{
Application.Exit();
}
}
I would do this the other way round.
In the OnLoad event for your Main form show the Logon form as a dialog. If the dialog result of that is OK then allow Main to continue loading, if the result is authentication failure then abort the load and show the message box.
EDIT Code sample(s)
private void MainForm_Load(object sender, EventArgs e)
{
this.Hide();
LogonForm logon = new LogonForm();
if (logon.ShowDialog() != DialogResult.OK)
{
//Handle authentication failures as necessary, for example:
Application.Exit();
}
else
{
this.Show();
}
}
Another solution would be to show the LogonForm from the Main method in program.cs, something like this:
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
LogonForm logon = new LogonForm();
Application.Run(logon);
if (logon.LogonSuccessful)
{
Application.Run(new MainForm());
}
}
In this example your LogonForm would have to expose out a LogonSuccessful bool property that is set to true when the user has entered valid credentials
This is my solution. Create ApplicationContext to set mainform of application and change mainform when you want to open new form and close current form.
Program.cs
static class Program
{
static ApplicationContext MainContext = new ApplicationContext();
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
MainContext.MainForm = new Authenticate();
Application.Run(MainContext);
}
public static void SetMainForm(Form MainForm)
{
MainContext.MainForm = MainForm;
}
public static void ShowMainForm()
{
MainContext.MainForm.Show();
}
}
When login process is complete.
private void BtLogin_Click(object sender, EventArgs e)
{
//Login Process Here.
Program.SetMainForm(new Portal());
Program.ShowMainForm();
this.Close();
}
I hope this will help you.
It's simple.
Here is the code.
private void button1_Click(object sender, EventArgs e)
{
//creating instance of main form
MainForm mainForm = new MainForm();
// creating event handler to catch the main form closed event
// this will fire when mainForm closed
mainForm.FormClosed += new FormClosedEventHandler(mainForm_FormClosed);
//showing the main form
mainForm.Show();
//hiding the current form
this.Hide();
}
// this is the method block executes when main form is closed
void mainForm_FormClosed(object sender, FormClosedEventArgs e)
{
// here you can do anything
// we will close the application
Application.Exit();
}
This is the most elegant solution.
private void buttonLogin_Click(object sender, EventArgs e)
{
MainForm mainForm = new MainForm();
this.Hide();
mainForm.ShowDialog();
this.Close();
}
;-)
Here's a simple solution, your problem is that your whole application closes when your login form closes right? If so, then go to your projects properties and on the Application Tab change the shutdown mode to "When last form closes" that way you can use Me.close without closing the whole program
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Login();
}
private static bool logOut;
private static void Login()
{
LoginForm login = new LoginForm();
MainForm main = new MainForm();
main.FormClosed += new FormClosedEventHandler(main_FormClosed);
if (login.ShowDialog(main) == DialogResult.OK)
{
Application.Run(main);
if (logOut)
Login();
}
else
Application.Exit();
}
static void main_FormClosed(object sender, FormClosedEventArgs e)
{
logOut= (sender as MainForm).logOut;
}
}
public partial class MainForm : Form
{
private void btnLogout_ItemClick(object sender, ItemClickEventArgs e)
{
//timer1.Stop();
this.logOut= true;
this.Close();
}
}
I think a much better method is to do this in the Program.cs file where you usually have Application.Run(form1), in this way you get a cleaner approach, Login form does not need to be coupled to Main form, you simply show the login and if it returns true you display the main form otherwise the error.
Try this:
public void ShowMain()
{
if(auth()) // a method that returns true when the user exists.
{
this.Close();
System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(Main));
t.Start();
}
else
{
MessageBox.Show("Invalid login details.");
}
}
[STAThread]
public void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Main());
}
You must call the new form in a diferent thread apartment, if I not wrong, because of the call system of windows' API and COM interfaces.
One advice: this system is high insecure, because you can change the if condition (in MSIL) and it's "a children game" to pass out your security. You need a stronger system to secure your software like obfuscate or remote login or something like this.
Hope this helps.
you should do it the other way round:
Load the mainform first and in its onload event show your loginform with showdialog() which will prevent mainform from showing until you have a result from the loginform
EDIT:
As this is a login form and if you do not need any variables from your mainform (which is bad design in practice), you should really implement it in your program.cs as Davide and Cody suggested.
best way for show login for and close login form before login successfully put login form in FrmMain after InitializeComponent.
public FrmMain()
{
FrmSplash FrmSplash = new FrmSplash();
FrmSplash.ShowDialog();
InitializeComponent();
//Login Section
{
public void ShowMain()
{
if(auth()) // a method that returns true when the user exists.
{
this.Hide();
var main = new Main();
main.Show();
}
else
{
MessageBox.Show("Invalid login details.");
}
}
try this
private void cmdLogin_Click(object sender, EventArgs e)
{
if (txtUserName.Text == "admin" || txtPassword.Text == "1")
{
FrmMDI mdi = new FrmMDI();
mdi.Show();
this.Hide();
}
else {
MessageBox.Show("Incorrect Credentials", "Library Management System", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
and when you exit the Application you can use
Application.Exit();
Evan the post is too old i like to give you a trick to do this if you wants to show splash/login screen and when the progress bar of splash screen get certain value/or successful login happen and closed the splash/login then re show the main form, frm-main will be the startup form not frm-spalash
in frm-main
public partial class frmMain : Form
{
public frmMain()
{
frmSplash frm = new frmSplash();
frm.Show(); // new splash screen will shows
this.Opacity=0; // will hide your main form
InitializeComponent();
}
}
in the frm-Splash
private void timer1_Tick(object sender, EventArgs e)
{
int cnt = progressBar1.Value;
switch (cnt)
{
case 0:
//Do sum stuff
break;
case 100:
this.Close(); //close the frm-splash
frmMain.ActiveForm.Opacity = 100; // show the frm-main
break;
}
progressBar1.Value = progressBar1.Value+1;
}
if you use it for login form
private void btlogin_Click(object sender, EventArgs e)
{
bool login = false;
//try your login here
//connect your database or whatever
//and then when it success update login variable as true
if(login == true){
this.Close(); //close the frm-login
frmMain.ActiveForm.Opacity = 100; // show the frm-main
}else{
//inform user about failed login
}
}
note that i use a timer and a progress bar to manipulate the actions you don't need those two it just for sake of complete answer only, hope this helps
1.Go to MainMenu Design properties> Go to my events
2.Click MainMenu event Shown and show LoginForm
3.Leave MainMenu as the First run in Program.cs
Related
I have two forms in my project (Login and Main).
What I'm trying to accoomplish is, if the login is successful, I must show the Main form and close the Login form.
I have this method in Login form that closes the Login form when the login is successful. But the Main form doesn't show.
public void ShowMain()
{
if(auth()) // a method that returns true when the user exists.
{
var main = new Main();
main.Show();
this.Close();
}
else
{
MessageBox.Show("Invalid login details.");
}
}
I tried hiding the Login form if the login process is successful. But it bothers me because I know while my program is running the login form is still there too, it should be closed right?
What should be the right approach for this?
Thanks...
The reason your main form isn't showing is because once you close the login form, your application's message pump is shut down, which causes the entire application to exit. The Windows message loop is tied to the login form because that's the one you have set as the startup form in your project properties. Look in your "Program.cs" file, and you'll see the responsible bit of code: Application.Run(new LoginForm()). Check out the documentation for that method here on MSDN, which explains this in greater detail.
The best solution is to move the code out of your login form into the "Program.cs" file. When your program first starts, you'll create and show the login form as a modal dialog (which runs on a separate message loop and blocks execution of the rest of your code until it closes). When the login dialog closes, you'll check its DialogResult property to see if the login was successful. If it was, you can start the main form using Application.Run (thus creating the main message loop); otherwise, you can exit the application without showing any form at all. Something like this:
static void Main()
{
LoginForm fLogin = new LoginForm();
if (fLogin.ShowDialog() == DialogResult.OK)
{
Application.Run(new MainForm());
}
else
{
Application.Exit();
}
}
I would do this the other way round.
In the OnLoad event for your Main form show the Logon form as a dialog. If the dialog result of that is OK then allow Main to continue loading, if the result is authentication failure then abort the load and show the message box.
EDIT Code sample(s)
private void MainForm_Load(object sender, EventArgs e)
{
this.Hide();
LogonForm logon = new LogonForm();
if (logon.ShowDialog() != DialogResult.OK)
{
//Handle authentication failures as necessary, for example:
Application.Exit();
}
else
{
this.Show();
}
}
Another solution would be to show the LogonForm from the Main method in program.cs, something like this:
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
LogonForm logon = new LogonForm();
Application.Run(logon);
if (logon.LogonSuccessful)
{
Application.Run(new MainForm());
}
}
In this example your LogonForm would have to expose out a LogonSuccessful bool property that is set to true when the user has entered valid credentials
This is my solution. Create ApplicationContext to set mainform of application and change mainform when you want to open new form and close current form.
Program.cs
static class Program
{
static ApplicationContext MainContext = new ApplicationContext();
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
MainContext.MainForm = new Authenticate();
Application.Run(MainContext);
}
public static void SetMainForm(Form MainForm)
{
MainContext.MainForm = MainForm;
}
public static void ShowMainForm()
{
MainContext.MainForm.Show();
}
}
When login process is complete.
private void BtLogin_Click(object sender, EventArgs e)
{
//Login Process Here.
Program.SetMainForm(new Portal());
Program.ShowMainForm();
this.Close();
}
I hope this will help you.
It's simple.
Here is the code.
private void button1_Click(object sender, EventArgs e)
{
//creating instance of main form
MainForm mainForm = new MainForm();
// creating event handler to catch the main form closed event
// this will fire when mainForm closed
mainForm.FormClosed += new FormClosedEventHandler(mainForm_FormClosed);
//showing the main form
mainForm.Show();
//hiding the current form
this.Hide();
}
// this is the method block executes when main form is closed
void mainForm_FormClosed(object sender, FormClosedEventArgs e)
{
// here you can do anything
// we will close the application
Application.Exit();
}
This is the most elegant solution.
private void buttonLogin_Click(object sender, EventArgs e)
{
MainForm mainForm = new MainForm();
this.Hide();
mainForm.ShowDialog();
this.Close();
}
;-)
Here's a simple solution, your problem is that your whole application closes when your login form closes right? If so, then go to your projects properties and on the Application Tab change the shutdown mode to "When last form closes" that way you can use Me.close without closing the whole program
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Login();
}
private static bool logOut;
private static void Login()
{
LoginForm login = new LoginForm();
MainForm main = new MainForm();
main.FormClosed += new FormClosedEventHandler(main_FormClosed);
if (login.ShowDialog(main) == DialogResult.OK)
{
Application.Run(main);
if (logOut)
Login();
}
else
Application.Exit();
}
static void main_FormClosed(object sender, FormClosedEventArgs e)
{
logOut= (sender as MainForm).logOut;
}
}
public partial class MainForm : Form
{
private void btnLogout_ItemClick(object sender, ItemClickEventArgs e)
{
//timer1.Stop();
this.logOut= true;
this.Close();
}
}
I think a much better method is to do this in the Program.cs file where you usually have Application.Run(form1), in this way you get a cleaner approach, Login form does not need to be coupled to Main form, you simply show the login and if it returns true you display the main form otherwise the error.
Try this:
public void ShowMain()
{
if(auth()) // a method that returns true when the user exists.
{
this.Close();
System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(Main));
t.Start();
}
else
{
MessageBox.Show("Invalid login details.");
}
}
[STAThread]
public void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Main());
}
You must call the new form in a diferent thread apartment, if I not wrong, because of the call system of windows' API and COM interfaces.
One advice: this system is high insecure, because you can change the if condition (in MSIL) and it's "a children game" to pass out your security. You need a stronger system to secure your software like obfuscate or remote login or something like this.
Hope this helps.
you should do it the other way round:
Load the mainform first and in its onload event show your loginform with showdialog() which will prevent mainform from showing until you have a result from the loginform
EDIT:
As this is a login form and if you do not need any variables from your mainform (which is bad design in practice), you should really implement it in your program.cs as Davide and Cody suggested.
best way for show login for and close login form before login successfully put login form in FrmMain after InitializeComponent.
public FrmMain()
{
FrmSplash FrmSplash = new FrmSplash();
FrmSplash.ShowDialog();
InitializeComponent();
//Login Section
{
public void ShowMain()
{
if(auth()) // a method that returns true when the user exists.
{
this.Hide();
var main = new Main();
main.Show();
}
else
{
MessageBox.Show("Invalid login details.");
}
}
try this
private void cmdLogin_Click(object sender, EventArgs e)
{
if (txtUserName.Text == "admin" || txtPassword.Text == "1")
{
FrmMDI mdi = new FrmMDI();
mdi.Show();
this.Hide();
}
else {
MessageBox.Show("Incorrect Credentials", "Library Management System", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
and when you exit the Application you can use
Application.Exit();
Evan the post is too old i like to give you a trick to do this if you wants to show splash/login screen and when the progress bar of splash screen get certain value/or successful login happen and closed the splash/login then re show the main form, frm-main will be the startup form not frm-spalash
in frm-main
public partial class frmMain : Form
{
public frmMain()
{
frmSplash frm = new frmSplash();
frm.Show(); // new splash screen will shows
this.Opacity=0; // will hide your main form
InitializeComponent();
}
}
in the frm-Splash
private void timer1_Tick(object sender, EventArgs e)
{
int cnt = progressBar1.Value;
switch (cnt)
{
case 0:
//Do sum stuff
break;
case 100:
this.Close(); //close the frm-splash
frmMain.ActiveForm.Opacity = 100; // show the frm-main
break;
}
progressBar1.Value = progressBar1.Value+1;
}
if you use it for login form
private void btlogin_Click(object sender, EventArgs e)
{
bool login = false;
//try your login here
//connect your database or whatever
//and then when it success update login variable as true
if(login == true){
this.Close(); //close the frm-login
frmMain.ActiveForm.Opacity = 100; // show the frm-main
}else{
//inform user about failed login
}
}
note that i use a timer and a progress bar to manipulate the actions you don't need those two it just for sake of complete answer only, hope this helps
1.Go to MainMenu Design properties> Go to my events
2.Click MainMenu event Shown and show LoginForm
3.Leave MainMenu as the First run in Program.cs
I have a Loginform which i coded into the mainform or Form1, then if all the inputed credentials are correct I will be directed to Form2 and then the Loginform will close, and the Form2 contains a logout button, and if I click the logout button I will go back to Loginform and input again the credentials.
I want to close or not to be shown in the taskbar icon the Loginform when I'm successfully login, I only want to see one icon not two icon in the taskbar.
Note:
Loginform is in the Form1, and Form2 is another form.
void btnLogin_Click(object sender, EventArgs e)
{
bool error = true;
if ((txtUserLog.Text.Trim() == "") || (txtPassLog.Text.Trim() == ""))
{
MessageBox.Show("Please fill all fields!");
}
cfgotcall.tether(settings);
cfgotcall.engageQuery("SELECT * FROM tblUsers");
unitbl = cfgotcall.tbl;
cfgotcall.untether();
for (int i = 0; i < unitbl.Rows.Count; i++)
{
if ((unitbl.Rows[i].ItemArray.ElementAt(2).ToString().Equals(txtUserLog.Text, StringComparison.OrdinalIgnoreCase)) && (unitbl.Rows[i].ItemArray.ElementAt(3).Equals(txtPassLog.Text)))
{
if (unitbl.Rows[i].ItemArray.ElementAt(4).ToString().Equals("Registrar", StringComparison.OrdinalIgnoreCase))
{
error = false;
i = unitbl.Rows.Count;
cfgotcall.engageQuery("SELECT * FROM tblUsers");
frmInterface sfInterface = new frmInterface();
sfInterface.enable_mnuSIM(true);
sfInterface.ShowDialog();
}
else if (unitbl.Rows[i].ItemArray.ElementAt(4).ToString().Equals("Accounting", StringComparison.OrdinalIgnoreCase))
{
error = false;
i = unitbl.Rows.Count;
cfgotcall.engageQuery("SELECT * FROM tblUsers");
frmInterface sfInterface = new frmInterface();
sfInterface.enable_mnuSAM(true);
sfInterface.ShowDialog();
}
}
Additional to the correct answer of #Slashy:
"Use Form1.Visible = False;" or "This.Visible = False;" because .Close() on the Mainform exists the whole program.
#Edit: ".Hide()" as #Slashy edited is also a possibility :)
You shouldn't continue after the showing the MessageBox as it wouldn't make any sense, so do something like:
if ((txtUserLog.Text.Trim() == "") || (txtPassLog.Text.Trim() == ""))
{
MessageBox.Show("Please fill all fields!");
return; // Abort continuing when no data entered
}
You can simply create a new instance of the second form and show it, simultaneously hiding the current form somthing like this:
//when login successed
Form2 form2=new Form2();
form2.Show();
this.Hide()//closes the current form.
Goodluck.
I think your approach just create more problems for your application when you need to handle login and main forms simultaneously.
On my opinion LoginForm must handle only login processing
and Main form will be shown only if LoginForm succesfully passed.
Main form and login form are different forms
Write your own Main method which will look like this:
public void Main()
{
using LoginForm login = new LoginForm()
{
if(login.ShowDialog() != DialogResult.Ok)
{
return;
}
}
//Show main form if login was succesfull
using Form1 main = new Form1()
{
main.ShowDialog();
}
}
private void buttonLogin_Click(object sender, EventArgs e)
{
MainForm mainForm = new MainForm();
this.Hide();
mainForm.ShowDialog();
this.Close();
}
ok guys thanks for your suggestion, i think i found the answer here it is and it's working on my code, a big thanks for those who help :)
this is the link:
it came from #Bhaggya Solangaarachchi
https://stackoverflow.com/a/31912692/5448305
I am working on a project (simple phonebook) for personal use.
Basically, I have got three forms: Main (the main one), Settings (the one used for configuring settings) and Login (the login form, which should start only if the user checked the option to be asked for the password on startup). Just to make the things clear: when the .EXE file is started it should load the Main form, unless the option to ask for pass is checked (Properties.Settings.Default.AskForPass == true) - when it should run the Login form first.
Here is what the login form looks like:
I have no idea how to make things work in the proper way.
I have tried to change the line in Program.cs from Main to Login:
namespace Phonebook
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Login());
}
}
}
and then if the user enters the right username and password and clicks the OK button:
private void button1_Click(object sender, EventArgs e)
{
if (txtUsername.Text == Properties.Settings.Default.MyUsername && txtPassword.Text == Properties.Settings.Default.MyPassword)
{
Main f1 = new Main();
Login f3 = new Login();
f1.Show();
f3.Close();
}
else
{
DialogResult dialogResult = MessageBox.Show("Wrong password! Do you want to try again?", "Warning", MessageBoxButtons.RetryCancel, MessageBoxIcon.Warning);
if (dialogResult == DialogResult.Retry)
{
return;
}
else if (dialogResult == DialogResult.Cancel)
{
this.Close();
}
}
}
the login form stays in the background, as you can see here:
I would like the Login form to be closed, so it doesn't appear in the background. The problem is that now the Login form is the main one and if I try to close it, the whole application shuts down.
I have tried changing the owner but had no success doing so.
Any ideas? Please, help!
You are creating a new Login form and closing that. Try
this.Hide();
f1.ShowDialog();
this.Close();
Another approach is to return a status on the Login Form and then check that and Application.Run() the Main form:
In the login form:
private bool LoggedIn;
public bool IsLoggedIn { get { return LoggedIn; } }
Then in the button click:
LoggedIn = true;
this.Close();
And in Program.cs:
Login f = new Login();
Application.Run(f);
if (f.IsLoggedIn)
Application.Run(new Main());
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
I created a login form in c#.
If a user signs in with the right password and username and clicks on 'Login' then the second form opens. How do I close the login form after the last step?
Change your Main() method in Program.cs to display the login dialog. Don't start the message loop unless a valid login was entered. For example:
static void Main() {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
using (var login = new LoginForm()) {
if (login.ShowDialog() != DialogResult.OK) return;
}
Application.Run(new Form1());
}
Your LoginForm should set its DialogResult property to OK if it detected a proper login.
You can type
FormName.ActiveForm.Close();
It closes the current active form.
You can call this.Close();
I would do a ShowDialog() of the Login Form from the main form.
After the login form closes you are back in the main form.
private void Form1_Load(object sender, EventArgs e)
{
var foo = new Form() { Text = "Login" };
if (foo.ShowDialog() == DialogResult.OK)
{
...
}
}