Search code examples
c#winformsmdiparentopenform

Form doesn't open as the active window


I have a main MDI form in my application and a login form. I'm opening my application like this. I want to open the login as the active form in which user should not be able to click any control of the MDI parent form while my login form is open. I open my login form like this in the MDI form.

Form newLogin = new FormControllers.FrmLogin();
newLogin.StartPosition = FormStartPosition.CenterScreen;
newLogin.Show(this);
newLogin.Focus();
newLogin.TopMost = true;
newLogin.Activate();

Then this is the code I have used in my login form:

public void activateParent() 
{
    if (this.Owner != null)
    {
        this.Owner.Enabled = true;
    }
}

private void FrmLogin_Activated(object sender, EventArgs e)
{
    if (this.Owner != null)
    {
        this.Owner.Enabled = false;
    }
}

private void FrmLogin_Deactivate(object sender, EventArgs e)
{
    activateParent();
}

private void FrmLogin_FormClosing(object sender, FormClosingEventArgs e)
{
    activateParent();
}

Still when I run the program login form opens, but not as active form. Just after I run my program my MDI form controllers can be accessed.
My MDI main disables only when I click on login form.I want to overcome this.
I want to open my MDI form disabled and login form activated.
How to achieve this?


Solution

  • use ShowDialog() instead of Show().

    E.g.

    newLogin.ShowDialog()
    

    And then you should add a check on login form if it is closed without authenticating a user it should close the whole application, or alternatively, you can hide title bar.