0

In my winform application; I have login form and main form.

When I run program I want the login form on top and main form behind it.

One more thing is until I do not login properly with username and password, the main form should not be accessible and only the login form should accessible.

My Language is C#.Net.

Please provide idea on how to achieve this?

Toon Krijthe
  • 52,876
  • 38
  • 145
  • 202

2 Answers2

2

Use Form.ShowDialog (Shows the form as a modal dialog box) on the your Form.OnShown event (Occurs whenever the form is first displayed):

private void Form1_Load(object sender, EventArgs e)
{
    this.Shown += Form1_Shown;
}

private void Form1_Shown(object sender, EventArgs e)
{
    LoginForm loginForm  = new LoginForm ();

    if (loginForm.ShowDialog() == DialogResult.Ok)
    {
     ....
    }
}

your Program and LoginForm like this:

//Progrmm.cs
Application.Run(new Form1());

//LoginForm.cs
public partial class LoginForm : Form
{
    public LoginForm ()
    {
        InitializeComponent();
    }

    private void buttonLogin_Click(object sender, EventArgs e)
    {
        //check username password
        if(texboxUser == "user" && texboxPassword == "password")
        {
            DialogResult = DialogResult.OK;
            Close();
        }
        else
        {
            MessageBox.Show("Wrong user pass");
        }
    }
}
Ria
  • 10,237
  • 3
  • 33
  • 60
0

I for one do not like the design you proposed, would want to first show the Login form, then the mainform. But if you absolutely need it, then you can do the below..

In Main class:

Application.Run(new frmMain());

And then in Form class:

private void frmMain_Load(object sender, EventArgs e)
{
    //---------------------------------------------


    System.Windows.Forms.Timer t = new System.Windows.Forms.Timer();
    t.Tick +=new EventHandler(t_Tick);
    t.Interval = 1000;
    t.Start();
}

void t_Tick(object sender, EventArgs e)
{
    frmLogin l = new frmLogin();
    if (l.ShowDialog(this) == DialogResult.Ok)
       ((System.Windows.Forms.Timer)sender.Dispose();
}

Though you have to further ensure that the login form is not exited without proper username and password (that should be upto you)

Use System.Windows.Forms.Timer because it runs in the same thread and hence would block the calls to main form (unlike System.Timers.Timer)

nawfal
  • 70,104
  • 56
  • 326
  • 368
  • System.Timers.Timer t = new System.Timers.Timer(1000); t.Elapsed += new System.Timers.ElapsedEventHandler(t_Elapsed); t.Start(); } void t_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { frmLogin l = new frmLogin(); if (l.ShowDialog() == DialogResult.Ok) ((System.Timers.Timer)sender.Dispose(); }where i put this code in login form or in main form – Pinakin Miyani Jul 30 '12 at 06:41
  • if (l.ShowDialog() == DialogResult.Ok) ((System.Timers.Timer)sender.Dispose(); this part is giveing me error. what should be code for login form? – Pinakin Miyani Jul 30 '12 at 06:49