首先聲明,這只是一種登錄方式,并不是最好的方式,用這個例子為了說明登錄窗體和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());}}}
}
登錄窗體的布局
登錄按鈕中要驗證當前用戶和密碼是否存在,存在的話,就把用戶保存在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,當然也可以定義其他屬性來完成。
本例中是說明一種思路,現實中的登錄方式各種各樣,有次數限制的,有與三方通信的,還有指紋人臉的,都是在最基礎上作增量。希望對你有所收獲。