[VB.NET]本機Windows帳號密碼驗證登入

在自已的電腦本機建立帳號密碼後,執行本程式,即可驗證剛建立的帳號密碼,如果要用AD驗證帳號密碼,.NET也有提供。

引入Windows系統的advapi32.dll宣告為Function後使用,在Button_OK按下後會執行LogonUser和參數的宣告,最後LogonUser會回傳True或False。

 


Public Class Form1

    Public Declare Auto Function LogonUser Lib "advapi32.dll" (ByVal lpszUsername As String, ByVal lpszDomain As String, ByVal lpszPassword As String, _
   ByVal dwLogonType As Integer, ByVal dwLogonProvider As Integer, ByRef phToken As IntPtr) As Boolean

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

    End Sub

    Private Sub Button_OK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button_OK.Click
        Dim UserID As String = TextBox_UserName.Text
        Dim UserPass As String = TextBox_Password.Text
        Dim bTemp As Boolean
        Dim MachineName As String

        MachineName = System.Environment.MachineName

        Const LOGON32_PROVIDER_DEFAULT As Integer = 0
        Const LOGON32_LOGON_INTERACTIVE As Integer = 2
        Dim tokenHandle As New IntPtr(0)
        tokenHandle = IntPtr.Zero

        bTemp = LogonUser(UserID, MachineName, UserPass, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, tokenHandle)

        If bTemp Then
            MsgBox("登入成功")
        Else
            MsgBox("登入失敗")
        End If
    End Sub
End Class

範本下載:AD.rar