参考VijosNT mini写的, 遵循GPLv3协议。
Imports System.Runtime.InteropServices Imports System.ComponentModel Public Class WinLogin #Region "credui.dll" Public Structure CREDUI_INFO Dim cbSize As Int32 Dim hwndParent As IntPtr <MarshalAs(UnmanagedType.LPTStr)> _ Dim MessageText As String <MarshalAs(UnmanagedType.LPTStr)> _ Dim CaptionText As String Dim hbmBanner As IntPtr End Structure Public Declare Auto Function CredUIPromptForCredentials Lib "credui.dll" ( _ ByRef UiInfo As CREDUI_INFO, _ ByVal TargetName As String, _ ByVal Reserved As IntPtr, _ ByVal dwAuthError As Int32, _ ByVal pszUserName As IntPtr, _ ByVal ulUserNameMaxChars As Int32, _ ByVal pszPassword As IntPtr, _ ByVal ulPasswordMaxChars As Int32, _ ByRef pfSave As Boolean, _ ByVal dwFlags As CredUIFlags) As Int32 Public Enum CredUIFlags As Int32 CREDUI_FLAGS_DO_NOT_PERSIST = &H2 CREDUI_FLAGS_ALWAYS_SHOW_UI = &H80 CREDUI_FLAGS_GENERIC_CREDENTIALS = &H40000 End Enum #End Region Public Const WINERROR_CANCELLED As Int32 = 1223 Public Shared Function PromptForCredentials(ByVal ParentWindow As IntPtr, ByVal Message As String, ByVal Title As String, ByRef UserName As String, ByRef Password As String) As DialogResult Const MaxLength As Int32 = 512 Dim CredUIInfo As New CREDUI_INFO CredUIInfo.cbSize = Marshal.SizeOf(CredUIInfo) CredUIInfo.hwndParent = ParentWindow CredUIInfo.MessageText = Message CredUIInfo.CaptionText = Title Dim UserNamePtr As IntPtr = Marshal.AllocHGlobal(MaxLength * Marshal.SystemDefaultCharSize) Try Marshal.WriteInt16(UserNamePtr, 0) Dim PasswordPtr As IntPtr = Marshal.AllocHGlobal(MaxLength * Marshal.SystemDefaultCharSize) Try Marshal.WriteInt16(PasswordPtr, 0) Dim LastErr As Int32 = CredUIPromptForCredentials(CredUIInfo, String.Empty, 0, 0, UserNamePtr, MaxLength, PasswordPtr, MaxLength, False, _ CredUIFlags.CREDUI_FLAGS_GENERIC_CREDENTIALS Or CredUIFlags.CREDUI_FLAGS_ALWAYS_SHOW_UI Or CredUIFlags.CREDUI_FLAGS_DO_NOT_PERSIST) Select Case LastErr Case 0 UserName = Marshal.PtrToStringAuto(UserNamePtr) Password = Marshal.PtrToStringAuto(PasswordPtr) Return DialogResult.OK Case WINERROR_CANCELLED Return DialogResult.Cancel Case Else Throw New Win32Exception(LastErr) End Select Finally Marshal.FreeHGlobal(PasswordPtr) End Try Finally Marshal.FreeHGlobal(UserNamePtr) End Try End Function End Class
调用方法:
Dim Username, Password As String If WinLogin.PromptForCredentials(0, "hello, world", "登录", Username, Password) <> DialogResult.OK Then 'TODO: blablabla End If
发表评论