Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Winform Forms Closing and opening a new form

Tags:

c#

forms

winforms

1. frmHome frm = new frmHome();
   frm.Show();
   this.Close();

I'm opening HomeForm from LoginForm. In LoginForm's form_closed event I call Application.Exit(). This allows you to open LoginForm and exit the application by clicking the X button.

The problem is when I move from LoginForm to HomeForm and call this.Close(), the form_closed event of LoginForm triggers and the application gets closed.

I am allowed to show only one form at a time.

like image 414
Karthick Avatar asked Nov 05 '09 00:11

Karthick


1 Answers

you can use a boolean (global variable) as exit flag in LoginForm

initialize it to :

exit = true;//in constructor

set it to false before closing:

frmHome frm = new frmHome();
frm.Show();
exit = false;
this.Close();

and in form_closed:

if(exit) Application.Exit();

if a user closes the form with the 'X' button, exit will have the value true, and Application.Exit() will be called.

EDIT:

the above is not working because LoginForm is your main form used by Application.Run(loginForm).

2 suggestions:

With exit flag:

replace

Application.Run(new LoginForm())

by

LoginForm loginFrm = new LoginForm();
loginFrm.Show();
Application.Run();

Without exit flag:

replace in your current code:

frmHome frm = new frmHome();
frm.Show();
this.Close();

by

frmHome frm = new frmHome();
this.Visible = false;
frm.ShowDialog();
this.Close();
like image 117
manji Avatar answered Sep 24 '22 14:09

manji