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 ?

1
  • 1
    How do you show the login form?
    – H H
    May 21, 2013 at 12:20

4 Answers 4

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
}
2
  • 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, 2013 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, 2013 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.

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

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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.