WinForm(四)一种实现登录的方式

首先声明,这只是一种登录方式,并不是最好的方式,用这个例子为了说明登录窗体和Application的关系。

在登录前,定义了用户实体,然后是一个通用的类,存放进程中当前登录的用户,所以CurrentUser是静态类。.

internal class User{    public int ID { get; set; }    public string? Name { get; set; }    public string? UserName { get; set; }    public string? Password { get; set; }}
internal class Common{    internal static User? CurrentUser { get; set; }}

这里的登录窗体不受Application管理,当登录成功后,会进入Application Run的主窗体。登录窗体要用ShowDialog模态化显示方式,让进程阻塞在登录窗体上,然后等待结束登录完成关闭后,获取登录窗体的对话窗结果,这里是如果Ok,定义为登录成功。

namespace WinFormDemo03{    internal static class Program    {        [STAThread]        static void Main()        {            ApplicationConfiguration.Initialize();
            var loginForm = new LoginForm();            if (loginForm.ShowDialog() == DialogResult.OK)            {                Application.Run(new MainForm());            }        }    }}

登录窗体的布局WinForm(四)一种实现登录的方式

登录按钮中要验证当前用户和密码是否存在,存在的话,就把用户保存在Common.CurrentUser中,以供后续主窗体或其他窗体使用,成功登录后要把当前窗体的DialogResult设置成Ok,因为在Main函数里,这就是判断登录的条件。

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms;using WinFormDemo03.Models;
namespace WinFormDemo03{    public partial class LoginForm : Form    {        private readonly List<User> _users;        public LoginForm()        {            _users = new List<User>()            {                new User{ ID=1,Name="桂素伟", UserName="gsw",Password="abc123" },                new User{ ID=2,Name="张三", UserName="zs",Password="123abc" }            };            InitializeComponent();        }
        private void loginButton_Click(object sender, EventArgs e)        {            Common.CurrentUser = _users.SingleOrDefault(s => s.UserName == usernameTextBox.Text && s.Password == passwordTextBox.Text);            if (Common.CurrentUser == null)            {                MessageBox.Show("用户名或密码错误,请重新输入!");            }            else            {                this.DialogResult = DialogResult.OK;            }        }    }}

登录的实现完成了:

1、登录是模态窗体,阻塞后台操作,登录成功,继续运行,失败,通出进程。

2、登录成功后要保留登录用户,以备后用。

3、登录成功与否是用了窗体的DialogResult,当然也可以定义其他属性来完成。

本例中是说明一种思路,现实中的登录方式各种各样,有次数限制的,有与三方通信的,还有指纹人脸的,都是在最基础上作增量。希望对你有所收获。