首页 > 代码库 > C#如何实现记住密码,自动登录功能?【转载】

C#如何实现记住密码,自动登录功能?【转载】

如何实现记住密码和自动登录功能?
技术分享

记住密码功能我是这样实现的:将用户名存入xml文件中,在窗体加载时读取并加入combobox的Items中,然后再在选择items中的某一项时,用combobox.Text做为条件从数据库读取密码(这样做是为了省去为xml文件加密,但不会影响速度!)!这是我自己实验过的,方法有点笨!
namespace address_list
{
    public partial class Addresslist : Form
    {
        public Addresslist()
        {
            InitializeComponent();
            this.skinEngine1.SkinFile = "CalmnessColor1.ssk";
        }

        private void btnlogin_Click(object sender, EventArgs e)
        {
            Login login = new Login();
            login.Show();
        }

        private void btnAdmin_Click(object sender, EventArgs e)
        {
            bool isValidUser = false;   // 标识是否为合法用户
            string message = "";        // 如果登录失败,显示的消息提示
            DBHelper.Username = cmbUserName.Text;//用户名文本框的内容,即用户名
            // 如果验证通过,就显示相应的用户窗体,并将当前窗体设为不可见
            if (ValidateInput())
            {
                // 调用用户验证方法
                isValidUser = ValidateUser(cmbUserName.Text, txtpwd.Text, ref message);

                // 如果是合法用户,显示相应的窗体
                if (isValidUser)
                {
                    // 将输入的用户名保存到静态变量中
                    UserHelper.loginId = cmbUserName.Text;
                    AddressAdmin chiefOpperate = new AddressAdmin();
                    chiefOpperate.Show();  // 显示相应用户的主窗体
                    this.Visible = false;
                }
                // 如果登录失败,显示相应的消息
                else
                {
                    MessageBox.Show(message, "登录失败", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }
        // 验证的结果有两种情况:通过和不通过,返回值为布尔型
        // 不通过的原因可能有多种,在方法的参数中增加消息字符串,用以标识不通过的情况
        /// <summary>
        /// 验证用户输入的用户名和密码是否正确
        /// </summary>
        /// <param name="loginId">登录用户名</param>
        /// <param name="loginPwd">登录密码</param>
        /// <param name="message">验证不通过的提示信息</param>
        /// <returns>true:验证通过。false:验证失败</returns>
        public bool ValidateUser(string loginId, string loginPwd, ref string message)
        {
            int count = 0;             // 数据库查询的结果
            bool isValidUser = false;  // 返回值,是否找到该用户

            // 查询用sql语句
            string sql = string.Format("SELECT COUNT(*) FROM Admin WHERE Username=‘{0}‘ AND pwd=‘{1}‘", loginId, loginPwd);

            try
            {
                // 创建Command命令
                SqlCommand command = new SqlCommand(sql, DBHelper.connection);
                DBHelper.connection.Open();  // 打开连接

                count = (int)command.ExecuteScalar();  // 执行查询语句

                // 如果找到1个,验证通过,否则是非法用户
                if (count == 1)
                {
                    isValidUser = true;
                }
                else
                {
                    message = "用户名或密码不存在!请重新输入!";
                    txtpwd.Clear();
                    isValidUser = false;
                }
            }
            catch (Exception ex)
            {
                message = ex.Message;
                MessageBox.Show(message, "异常提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
            }
            finally
            {
                DBHelper.connection.Close(); // 关闭数据库连接
            }
            return isValidUser;
        }



        /// <summary>
        /// 验证用户是否进行了输入
        /// </summary>
        /// <returns>验证成功返回True,失败返回False</returns>
        private bool ValidateInput()
        {
            if (cmbUserName.Text.Trim() == "")
            {
                MessageBox.Show("请输入用户名", "输入提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                cmbUserName.Focus();
                return false;
            }
            else if (txtpwd.Text.Trim() == "")
            {
                MessageBox.Show("请输入密码", "输入提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                txtpwd.Focus();
                return false;
            }
            else
            {
                return true;
            }
        }

        /// <summary>
        /// 连接到窗体:通过密码保护信息找回密码!
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lbl_mibao_Click(object sender, EventArgs e)
        {
            Getbackpwd getbackpwd = new Getbackpwd();
            getbackpwd.Show();
        }

        /// <summary>
        /// 当该窗体加载时从xml文件中读取用户信息并加载到combox的Items中
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Addresslist_Load(object sender, EventArgs e)
        {
            XmlTextReader reader = new XmlTextReader(@"E:\面向对象--C#练习\通讯录\address list\address list\user.xml");
            while (reader.Read())
            {
                //if (reader.LocalName.Equals("Name") || reader.LocalName.Equals("Number"))
                if (reader.LocalName.Equals("username"))
                {
                    this.cmbUserName.Items.Add(reader.ReadString());
                }
                //if (reader.LocalName.Equals("Number"))
                //{
                //    this.label2.Text += reader.ReadString() + "\n";
                //}
            }
            reader.Close();
        }

        
        /// <summary>
        /// 保存用户名到user.xml
        /// </summary>
        //在listcontol上更改SelectedValue时执行从数据库读取密码的事件
        private void cmbUserName_SelectedValueChanged(object sender, EventArgs e)
        {
            string username = cmbUserName.Text.Trim();
            string sql = string.Format("select pwd from Admin where Username=‘{0}‘", username);
            try
            {
                SqlCommand command = new SqlCommand(sql, DBHelper.connection);
                DBHelper.connection.Open();
                SqlDataReader dataReader = command.ExecuteReader();
                while (dataReader.Read())
                {
                    txtpwd.Text = (string)dataReader["pwd"];
                    checkBoxpwd.Checked = true;
                }
            }
            catch
            {
                MessageBox.Show("数据库操作出错!");
            }
            finally
            {
                DBHelper.connection.Close();
            }
        }
        /// <summary>
        /// 记住密码操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void checkBoxpwd_Enter(object sender, EventArgs e)
        {
            bool check = true;
            check = checkinput(cmbUserName.Text.Trim());
            if ((string)cmbUserName.Text.Trim() == "")
            {
                MessageBox.Show("请输入用户名", "输入提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                cmbUserName.Focus();
            }
            else
            {
                if (txtpwd.Text.Trim() == "")
                {
                    MessageBox.Show("请输入密码", "输入提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    txtpwd.Focus();
                }
                else
                {
                    bool isValidUser = false;   // 标识是否为合法用户
                    string message = "";        // 如果登录失败,显示的消息提示
                    // 如果验证通过,就显示相应的用户窗体,并将当前窗体设为不可见
                    if (ValidateInput())
                    {
                        // 调用用户验证方法
                        isValidUser = ValidateUser(cmbUserName.Text, txtpwd.Text, ref message);

                        // 如果是合法用户,显示相应的窗体
                        if (isValidUser)
                        {
                            if (check == true)
                            {
                                XmlDocument doc = new XmlDocument();
                                doc.Load(@"E:\面向对象--C#练习\通讯录\address list\address list\user.xml");
                                XmlElement node = doc.CreateElement("user");

                                XmlNode xnode = (XmlNode)doc.CreateElement("username");
                                xnode.InnerText = cmbUserName.Text.Trim();
                                node.AppendChild(xnode);

                                doc.DocumentElement.InsertAfter(node, doc.DocumentElement.LastChild);

                                doc.Save(@"E:\面向对象--C#练习\通讯录\address list\address list\user.xml");
                                //doc.Load (@"E:\面向对象--C#练习\通讯录\address list\address list\user.xml");
                            }
                        }
                        // 如果登录失败,显示相应的消息
                        else
                        {
                            MessageBox.Show(message, "记住密码失败!", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                    }
                    
                }
            }
        }

        /// <summary>
        /// 验证当前combox中内容是否已经存在于xml文件中
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        private bool checkinput(string text)
        {
            int count;
            bool c = true;
            for (count = 0; count < cmbUserName.Items.Count;count ++ )
            {
                if (text ==(string )cmbUserName .Items [count])
                {
                    c=false;
                }
            }
            return c;
        }
    }
}

C#如何实现记住密码,自动登录功能?【转载】