2014-10-02 62 views
-2

我想創建一個登錄表單,我已經預先定義了密碼。Visual basic登錄表單查詢(3次嘗試後關閉程序)

不過,我想只允許用戶3次嘗試在登錄後,如果他們失敗了,它會說,你用你的三次嘗試,並計劃將關閉,這是我到目前爲止的代碼:

Private Sub btnLogin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLogin.Click 
    Dim Password As String 
    Dim x As String 
    Dim Attempts As Integer 
    'maybe use for loop 
    Password = "House" 
    x = txtPassInput.Text 

    If Attempts = 3 Then 
     Me.Close() 
    End If 

    If x = Password Then 
     MsgBox("Correct password, you are now logged in.") 

    Else 
     Attempts = Attempts + 1 
     MsgBox("You have entered the wrong password.") 

    End If 

End Sub 

我在問什麼,我如何在3次嘗試後關閉它,我的程序還沒有這樣做。

+0

不要在過程中在本地聲明'嘗試',在窗體中聲明它。否則,該變量僅在運行例程時才存在,這意味着只有在例程啓動時纔會變爲0,如果嘗試失敗,則只會變爲1。 http://msdn.microsoft.com/en-us/library/ms973875.aspx – LittleBobbyTables 2014-10-02 18:09:56

+0

非常感謝你,我真的很感謝你的幫助!因爲我們不得不改變11年級GCSE的編程語言,所以我是新的Visual Basic。 – Finn 2014-10-02 18:12:19

回答

0
Dim LoginAttempts As Integer 
Dim currentPassword As String = "House" 

Private Sub Login(ByVal passwordFromTextBox As String) 
    If Not TestLoginForCompare(passwordFromTextBox) Then 
     LoginAttempts += 1 
     If LoginAttempts = 3 Then 
      'close form/program, return error, lock account 
     else 
      'notify user of failed attempt 
     End If 
    Else 
     LoginAttempts = 0 
     'proceed to success login 
    End If 
End Sub 
Private Function TestLoginForCompare(ByVal password As String) As Boolean 
    If String.Compare(currentPassword, password) Then 
     Return True 
    Else 
     Return False 
    End If 
End Function 
+0

實際上,string.compare可以在Login方法中實現而不會破壞SOLID原則。我把它們分成偏好但這不一定是必要的。 – 2014-10-02 18:32:38