2012-02-03 117 views

回答

11

在您的登录表单中,我假设您在按钮控件的Click事件方法内执行验证。所以,你会碰到这样的:这个代码的

Private Sub btnLogin_Click() 
    If ValidatePassword(txtPassword.Text) Then 
     ' The password is correct, so show the main form and close the login form 
     MainForm.Show 
     Unload Me 
    Else 
     ' The password is incorrect, so leave this form on screen 
     MsgBox "Invalid password entered!", vbError 
     txtPassword.SetFocus 
    End If 
End Sub 

两个有趣的特点是:

  1. Show方法,你要显示窗体对象调用。
    在这种情况下,它可能会成为您的主要形式 - 用所谓的任何东西代替MainForm

  2. Unload声明,它关闭并销毁指定的表单。
    在这种情况下,Me指的是登录表单,因为您完成了它。

+1

+1好例子 – 2012-02-03 04:49:40

1

我的方法是避免尝试打开登录窗体作为第一个窗体。

取而代之让主窗体成为第一个,并在其Load事件中将您的登录窗体显示为模态对话框。这可以通过对其进行显示来首先显示主窗体。基于标准模板 “登录对话框的” 形式与一些代码的变化举例:

frmMain.frm

Option Explicit 

Private Sub Form_Load() 
    Dim Control As Control 

    Show 
    frmLogin.Show vbModal, Me 
    With frmLogin 
     txtSuccess.Text = CStr(.LoginSucceeded) 
     If .LoginSucceeded Then 
      'Proceed normally, perhaps after capturing 
      'the User Name, etc. 
      txtUserName.Text = .User 
      txtPassword.Text = .Password 
     Else 
      'Do "Unload Me" or disable all controls 
      'as shown here, etc. 
      For Each Control In Controls 
       On Error Resume Next 
       Control.Enabled = False 
       On Error GoTo 0 
      Next 
     End If 
    End With 
    Unload frmLogin 
End Sub 

frmLogin.frm

Option Explicit 

Public LoginSucceeded As Boolean 
Public User As String 
Public Password As String 

Private Sub cmdCancel_Click() 
    LoginSucceeded = False 
    Hide 
End Sub 

Private Sub cmdOK_Click() 
    'Check for correct password, hard-coded here. 
    If txtPassword.Text = "password" Then 
     LoginSucceeded = True 
     User = txtUserName.Text 
     Password = txtPassword.Text 
     Hide 
    Else 
     MsgBox "Invalid Password, try again!", , "Login" 
     With txtPassword 
      .SetFocus 
      .SelStart = 0 
      .SelLength = Len(.Text) 
     End With 
    End If 
End Sub 
+0

模态对话框可能是一个更好的解决方案。我的回答假定提问者已经有了什么,这并不总是最好的方法! – 2012-02-05 00:49:28

+0

这不需要从Form_Load完成,它可以很容易地是菜单或按钮启动登录的结果......假设在登录之前让表单可见并且处于活动状态需要很多时间。也许在一次运行期间登录具有不同凭据的串行会话。 – Bob77 2012-02-05 18:06:05

相关问题