C#实现Windows系统账户密码登录


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Text;
using System.Windows.Forms;
namespace WindowsLogin
{
public partial class FormLogin : Form
{
[DllImport("advapi32.dll", CharSet = CharSet.Auto)]
public static extern bool LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, out int phToken);
public FormLogin()
{
InitializeComponent();
}
private void FormLogin_Load(object sender, EventArgs e)
{
textBoxUser.Text = Environment.UserName;
textBoxDomain.Text = Environment.UserDomainName;
textBoxPwd.Focus();
}
private void btnLogin_Click(object sender, EventArgs e)
{
//验证用户的输入是否为空
if (textBoxDomain.Text.Trim().Length > 0 && textBoxUser.Text.Trim().Length > 0 && textBoxPwd.Text.Trim().Length > 0)
{ //调用函数Login(string UserName, string Password, string Domain)
//实现Windows登录
if (Login(textBoxUser.Text.Trim(), textBoxPwd.Text.Trim(), textBoxDomain.Text.Trim()) == true)
{ //显示登录成功信息
MessageBox.Show("登录成功!!!");
return;
}
else
{ //显示登录失败信息
MessageBox.Show( "登录失败,请重新输入用户名称、密码及其系统域名!!!");
}
}
}
private bool Login(string UserName, string Password, string Domain)
{ //获取用户名称和系统域名
string text1 = Domain.Trim();
string text2 = UserName.Trim();
text2 = text2.Replace("/", @"\"); //处理符号“/”
int num1 = text2.IndexOf('\\'); //获取符号“\”的索引
if (num1 != -1)
{ //格式化用户名称和系统域名
text1 = text2.Substring(0, num1);
text2 = text2.Substring(num1 + 1);
}
else
{ //格式化用户名称和系统域名
num1 = text2.IndexOf('@');
if (num1 != -1)
{
text1 = text2.Substring(num1 + 1);
text2 = text2.Substring(0, num1);
}
}
//调用函数AuthenticateUser()实现用户Windows登录
return AuthenticateUser(text2, Password.Trim(), text1);
}
private bool AuthenticateUser(string UserName, string Password, string Domain)
{ //设置用户登录成功的标志
bool flag1 = false;
try
{
int num1; IntPtr ptr1;
//调用Windows登录的API
if (!LogonUser(UserName, Domain, Password, 2, 0, out num1))
{ //返回登录结果
return flag1;
}
//调用.NET中的Windows登录
ptr1 = new IntPtr(num1);
WindowsIdentity identity1 = new WindowsIdentity(ptr1);
WindowsPrincipal principal1 = new WindowsPrincipal(identity1);
flag1 = true;
}
catch (Exception) { }
return flag1;
}
}
}点击阅读全文
《C#实现Windows系统账户密码登录》.doc
将本文下载保存,方便收藏和打印
导出文档
