1.在Program.cs文件类新增如下方法:
1 public static class Program 2 { 3 public static GlobalControl gc = new GlobalControl(); //存储全局变量类 4 5 /// <summary> 6 /// 应用程序的主入口点。 7 /// </summary> 8 [STAThread] 9 private static void Main() 10 { 11 Application.EnableVisualStyles(); 12 Application.SetCompatibleTextRenderingDefault(false); 13 14 LoginMain(); 15 16 } 17
//登录方法 18 public static void LoginMain() 19 { 20 FrmLogin frmLogin = new FrmLogin(); 21 22 if (frmLogin.ShowDialog() == DialogResult.OK) 23 { 24 Application.Run(new FrmMain()); 25 26 } 27 frmLogin.Dispose(); 28 } 29 }
2.新建一个全局变量类
public class GlobalControl { public BaseInfo baseInfo = null; //存储实例对象 }
3.在登录FrmLogin界面编写登录逻辑:
1 private void button1_Click(object sender, EventArgs e) 2 { 3 qqId = long.Parse(textBox1.Text); 4 try 5 { 6 7 if (qqUserService.Login(qqId, textBox2.Text)) 8 { 9 Program.gc.baseInfo = qqUserService.GetBaseInfo(qqId); //存储对象至全局变量类 10 this.DialogResult = DialogResult.OK; 11 } 12 else 13 { 14 MessageBox.Show("账户或者密码不正确"); 15 } 16 } 17 catch (Exception exception) 18 { 19 Console.WriteLine(exception.Message); 20 } 21 22 }
3.主界面FrmMain获取存储的对象:
1 //获取全局变量类中的登录对象 2 private readonly BaseInfo _baseInfo = Program.gc.baseInfo; 3 4 public FrmMain() 5 { 6 InitializeComponent(); 7 8 Load += FrmMain_Load; 9 } 10 11 private void FrmMain_Load(object sender, EventArgs e) 12 { 13 label1.Text =$"{ _baseInfo.NickName},欢迎您登录"; 14 }