[英]How to open another Form from current Form?
我们的第一个表单是“登录”表单。.登录后如何打开下一个表单?
In your log-in form, I assume you perform your validation inside of the Click
event method for a button control. 在您的登录表单中,我假设您在按钮控件的Click
事件方法内执行验证。 So you would have something like: 因此,您将获得以下内容:
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
The two interesting features of this code are: 该代码的两个有趣的功能是:
The Show
method, which you call on the form object that you want to show. Show
方法,在要显示的表单对象上调用。
In this case, it will probably be your main form—replace MainForm
with whatever it is called. 在这种情况下,它可能是您的主要形式-用它所调用的内容替换MainForm
。
The Unload
statement, which closes and destroys the specified form. Unload
语句,它将关闭并销毁指定的表单。
In this case, Me
refers to the login form since you're finished with it. 在这种情况下,由于您已完成登录,因此Me
参考登录表单。
You will need call Show
on the form which needs to be displayed post login form. 您需要在登录后需要Show
的表单上调用Show
。 You can read more about Understanding Forms and form events 您可以阅读有关了解表单和表单事件的更多信息
My approach is to avoid trying to open a logon Form as the first Form. 我的方法是避免尝试将登录表单作为第一个表单打开。
Instead let the main Form be first, and in its Load event Show your logon Form as a modal dialog. 而是让主窗体位于第一位,并在其Load事件中将您的登录窗体显示为模式对话框。 This can be done revealing the main Form first by doing a Show on it. 可以先在主窗体上进行显示,以显示主窗体。 Example based on the standard template "Log in Dialog" Form with some code changes: 基于标准模板“登录对话框”表单的示例,其中包含一些代码更改:
frmMain.frm 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 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.