C # - Close Form without Stop Application

3

Hello, I'm using C # to create a login system. And I would like to know some formula to close this login window without stopping the application. I used this.Hide (); to hide the form, but when closing the program it keeps running only hidden. Can someone help me? Remember that typing the correct username and password will call another form.

This is the code I am using:

if (usuarioTextBox.Text == "Administração" && senhaTextBox.Text == "@dmin321")
            {
               MessageBox.Show("Acesso Permitido");
               this.Hide();
               Form2 novoFormulario = new Form2();
               novoFormulario.Show();
            }
    
asked by anonymous 16.03.2017 / 03:30

3 answers

2

You can change from .Show() to .ShowDialog() and close your form when the second form is disposed :

if (usuarioTextBox.Text == "Administração" && senhaTextBox.Text == "@dmin321")
{
    MessageBox.Show("Acesso Permitido");
    Hide();
    Form2 novoFormulario = new Form2();
    novoFormulario.ShowDialog();
    if(novoFormulario.IsDisposed)
        Close();
}

In addition, in the second form, you must call the Dispose(); method in the FormClosing event:

private void Form2_FormClosing(Object sender, FormClosingEventArgs e) 
{
    Dispose();
}

When you call the Dispose(); method, you ensure that all the features used by the second form have been closed / closed.

    
16.03.2017 / 10:08
2

When you want to completely shut down your application use Application Exit , you can place it in the FormClosed event of the form (s):

private void Form1_FormClosed(object sender, FormClosedEventArgs e)
    {
        Application.Exit();
    }

That way, every application will be shut down.

    
16.03.2017 / 12:34
2

Tip: Why instead of calling the login form first, it does not start with the second so it can call the login and get login permission to continue! you can change the first form to be called in Program.cs

static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form2 ());
    }

Exchanging Form1 by Form2

and no form load can call Form1 (Login)

Visible = false;
Form1 Login= new Form1();
          Login.ShowDialog();

closing with some condition of true or false to make the form visible or not (if login is allowed)

    
16.03.2017 / 14:32