WinFrom 登陆窗体 保存密码效果 开发CS程序的程序员都会遇到 今天忽然想把这个功能加到个人项目中 以后总结下 很少说 上图程序员
若是关闭程序 下次在登陆的时候 用户名、密码会自动保留下来 一个类(User) 一个方法(DisplayUserInfo) 代码分为4个事件 ide
一、User 类spa
1 [Serializable] 2 public class User 3 { 4 5 private string loginID; 6 public string LoginID 7 { 8 get { return loginID; } 9 set { loginID = value; } 10 } 11 12 private string pwd; 13 public string Pwd 14 { 15 get { return pwd; } 16 set { pwd = value; } 17 } 18 }
二、DisplayUserInfo 方法code
1 //显示用户所对应匹配的信息 2 private void DisplayUserInfo() 3 { 4 5 string key = combox1.Text.Trim(); 6 //查找用户Id 7 if (users.ContainsKey(key) == false) 8 { 9 txtPwd.Text = ""; 10 return; 11 } 12 //查找到赋值 13 User user = users[key]; 14 txtPwd.Text = user.Pwd; 15 // 若有有密码 选中复选框 16 chkcaes.Checked = txtPwd.Text.Trim().Length > 0 ? true : false; 17 }
三、窗体 Load 事件orm
1 Dictionary<string, User> users = new Dictionary<string, User>(); 2 private void frmMain_Load(object sender, EventArgs e) 3 { 4 //读取文件流对象 5 FileStream fs = new FileStream("data.bin", FileMode.OpenOrCreate); 6 if (fs.Length > 0) 7 { 8 BinaryFormatter bf = new BinaryFormatter(); 9 //读出存在Data.bin 里的用户信息 10 users = bf.Deserialize(fs) as Dictionary<string, User>; 11 //循环添加到Combox1 12 foreach (User user in users.Values) 13 { 14 combox1.Items.Add(user.LoginID); 15 } 16 17 //combox1 用户名默认选中第一个 18 if (combox1.Items.Count > 0) 19 combox1.SelectedIndex = combox1.Items.Count-1; 20 } 21 fs.Close(); 22 }
四、登陆按钮 Click 事件对象
1 private void butOK_Click(object sender, EventArgs e) 2 { 3 User user = new User(); 4 // 登陆时 若是没有Data.bin文件就建立、有就打开 5 FileStream fs = new FileStream("data.bin", FileMode.OpenOrCreate); 6 BinaryFormatter bf = new BinaryFormatter(); 7 // 保存在实体类属性中 8 user.LoginID = combox1.Text.Trim(); 9 //保存密码选中状态 10 if (chkcaes.Checked) 11 user.Pwd = txtPwd.Text.Trim(); 12 else 13 user.Pwd = ""; 14 //选在集合中是否存在用户名 15 if (users.ContainsKey(user.LoginID)) 16 { 17 //若是有清掉 18 users.Remove(user.LoginID); 19 } 20 //添加用户信息到集合 21 users.Add(user.LoginID, user); 22 //写入文件 23 bf.Serialize(fs, users); 24 //关闭 25 fs.Close(); 26 MessageBox.Show("保存密码成功!请关闭窗体看效果"); 27 }
五、用户名下拉框 SelectedIndexChanged 事件blog
1 //当用户名下拉选项发生改变时 2 private void combox1_SelectedIndexChanged(object sender, EventArgs e) 3 { 4 DisplayUserInfo(); 5 }
六、用户名下拉框 TextChanged事件事件
1 //当用户名文本发生改变时 2 private void combox1_TextChanged(object sender, EventArgs e) 3 { 4 DisplayUserInfo(); 5 6 }
以上 就是 WinForm 保存密码 功能的全部代码 ip
Demo地址:http://files.cnblogs.com/yhyjy/%E8%AE%B0%E4%BD%8F%E5%AF%86%E7%A0%81.zip开发
以上供新手参考 若有好的方式 请留下您宝贵的思想与建议