0

Thanks to everyone who takes effort on answering my question.

I'm using WinForms C#, and on the MainForm_Load, I'm calling the Login form for the user. The Login form contains the X button (the default button on the top-right) and Loginbutton.

Now...

If the user decides to click on the X button the Login form closes and so should the MainForm, which I know how to do. But... if the user clicks on LoginButton the LoginForm should close, but the MainForm should stay opened.

Any idea hwo to do that ?

Etrit
  • 865
  • 2
  • 14
  • 25

4 Answers4

5

Assuming you are using ShowDialog to show the login form, then you can do this:

if(LoginForm.ShowDialog() == DialogResult.OK)
{
   //login ok
}

your login form should set the DialogResult to OK before it closes, but only for successful login, like so:

if(LoginSuccess){
    this.DialogResult = DialogResult.OK;//this will also close the form
}
musefan
  • 47,875
  • 21
  • 135
  • 185
  • 3
    You don't need the Close() call; setting DialogResult automatically hides the form and returns execution to the ShowDialog() line. – Idle_Mind May 21 '13 at 12:23
  • @Idle_Mind: Huh... never knew that. I don't like it though, not a behaviour I would expect from setting a property – musefan May 21 '13 at 12:34
3

You can check e.CloseReason in the Form.FormClosing event!

Private Sub YourForm_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
    If e.CloseReason = CloseReason.UserClosing Then
        'Closed by user
        '
        'Do something like
        'Application.Exit()
        '
        'or close both forms
    Else
        'Other close reason
    End If
End Sub

The CloseReason will be UserClosing if the X is clicked or the user presses Alt + F4.

Abandoned account
  • 1,855
  • 2
  • 16
  • 22
2

This is an alternative option :

You can disable the X button in login form by setting the ControlBox property of login form to False

Praveen VR
  • 1,554
  • 2
  • 16
  • 34
0

On your Login button's click event handler, add a call to this.Close()

This should close the Login form, without affecting the Main form.

Chris Spicer
  • 2,144
  • 1
  • 13
  • 22