簡體   English   中英

如何從當前表格中打開另一個表格?

[英]How to open another Form from current Form?

我們的第一個表單是“登錄”表單。.登錄后如何打開下一個表單?

在您的登錄表單中,我假設您在按鈕控件的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參考登錄表單。

您需要在登錄后需要Show的表單上調用Show 您可以閱讀有關了解表單和表單事件的更多信息

我的方法是避免嘗試將登錄表單作為第一個表單打開。

而是讓主窗體位於第一位,並在其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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM