Showing Login form before main form in vb.net

15,679

Solution 1

You could just set the startup form to the login form. Then when the user hits "OK" and is verified, you just load the main form and close the login form.

Alternatively you can use the "ShowDialog" method to show the form modally. In your login form code, you can set DialogResult when closing the form, which becomes the return value from the ShowDialog method. That way you can detect that, say, "Cancel" was pressed and quit.

UPDATE: Perhaps if you change your Sub Main to just:

Application.Run(YourLoginForm)

Along with whatever other startup code your require. Then handle showing the main form in your login form (if I remember correctly, your application will not exit until the last form closes... You can use that to your advantage).

Solution 2

I think your approach is fine, except for one thing: the loop. Instead, display the login form using ShowDialog.

Shared Sub Main()
    Dim authenticated As Boolean
    Using frmLogin1 As New LoginForm
        frmLogin1.ShowDialog()
        authenticated = frmLogin1.Authenticated
    End Using

    If authenticated Then
        ModuleRegistration.Register()
        Application.Run(MainForm)
    End If
End Sub
Share:
15,679
Dennis
Author by

Dennis

Updated on June 04, 2022

Comments

  • Dennis
    Dennis almost 2 years

    I'm sure I'm doing my login process for my app in a not so perfect way, but as with lots of things, it works. The issue is to make it work I have to use the very unpopular DoEvents thing.

    I would like my application to show a login screen before loading my main form. Currently I have a login dialog box with a FormOpen boolean property and an authenticated boolean property. If a user logs in successfully, I hide the login form, set formopen to false, and authenticated to true. If they cancel out, then I do the same and just set the authenticated property to false. If authenticated=false then I end the app, else I show the main form via application.run(MainForm)

    Shared Sub Main()
    
    Using frmLogin1 As New LoginForm
        frmLogin1.Show()
        Do While frmLogin1.FormOpen = True
            Application.DoEvents()
        Loop
    
        If frmLogin1.Authenticated = False Then End
    End Using
    
    ModuleRegistration.Register()
    Application.Run(MainForm)
    
    End Sub
    

    Is there a more preferred way of doing this?

  • Dennis
    Dennis over 14 years
    Thanks for the prompt response. I had an issue using showdialog though. IIRC, the problem with that was I have a button on my login form that is used to add/change database configuration for my app that I opened with showdialog. When the dbconfig form sent a dialogresult it caused sub main to continue processing. Even if the parent of dbconfig was login.
  • Matthew Iselin
    Matthew Iselin over 14 years
    Updated my answer to respond to your comment.