I am trying to make a form that verifies user login. I want that form to show first then, if the user login is successful, the main form should show.
this is what I have tried(in the second form):
private void button1_Click(object sender, EventArgs e)
{
string funame = "thename";
string dep = "thedep";
string unm = "theusername";
string ups = "thepassword";
User cs = new User(funame, dep, unm, ups);
if (cs.validateLogin(unm, ups));
{
MessageBox.Show("Welcome " + funame + " of " + dep);
frmPurchaseDiscountedItem fpd = new frmPurchaseDiscountedItem();
fpd.Show();
}
}
The problem is the main form always pops out first.
It should be something like:
*2nd form pops up then, if user is verified, main form pops up
Here is a workaround.
You don't need to change "start form" in Program.cs
. You can open the main window at the beginning and hide it. Then create a Login instance and show it.
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
Login login = new Login(this);
// hide MainForm
this.Hide();
// show Login
login.ShowDialog();
}
}
If login button in Login form
clicked, show the MainForm
and close Login form
.
public partial class Login : Form
{
private MainForm mainform = null;
public Login(MainForm main)
{
InitializeComponent();
// get MainForm instance
this.mainform = main;
}
// if success
bool success = true;
private void btnLogin_Click(object sender, EventArgs e)
{
if(success) // check login here
{
// show main form
mainform.Visible = true;
// close login form
this.Close();
}
}
}
In addition, if you click the X button
in the upper right corner of the Login form
, it will also show the hidden MainForm
(if user doesn't want to login, close the application). We can avoid it by overriding WndProc
.
protected override void WndProc(ref Message msg)
{
const int WM_SYSCOMMAND = 0x0112;
const int SC_CLOSE = 0xF060;
if (msg.Msg == WM_SYSCOMMAND && ((int)msg.WParam == SC_CLOSE))
{
// click the 'X' button to close the application
Application.Exit();
return;
}
base.WndProc(ref msg);
}