用winform做程序的时候,我们一般都是在Program先启动登录窗体,然后登录成功后才创建主窗体,结果这就导致了登录窗体无法关闭
所以如果我们不在Program的程序入口先创建登录窗体的话就能完美实现登录成功后关闭登录窗体的功能了,直接贴代码
usingSystem; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.Threading.Tasks; usingSystem.Windows.Forms; namespaceWindowsFormsApplication1 { static classProgram { /// <summary> ///应用程序的主入口点。 /// </summary> [STAThread] static voidMain() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new MainForm()); //程序启动于主窗体,而非登录窗体 } } }
usingSystem; usingSystem.Collections.Generic; usingSystem.ComponentModel; usingSystem.Data; usingSystem.Drawing; usingSystem.Linq; usingSystem.Text; usingSystem.Threading.Tasks; usingSystem.Windows.Forms; namespaceWindowsFormsApplication1 { public partial classLoginForm : Form { public MainForm mainForm; //获得主窗体引用,可以更新主窗体的登录标志 publicLoginForm() { InitializeComponent(); } private void button1_Click(objectsender, EventArgs e) { if (textBox1.Text == "admin") { mainForm.isLogin = true; this.Close(); //登陆成功则关闭登录窗体 } else{ MessageBox.Show("密码错误!"); } } } }
usingSystem; usingSystem.Collections.Generic; usingSystem.ComponentModel; usingSystem.Data; usingSystem.Drawing; usingSystem.Linq; usingSystem.Text; usingSystem.Threading.Tasks; usingSystem.Windows.Forms; namespaceWindowsFormsApplication1 { public partial classMainForm : Form { public bool isLogin = false; //登录标志 publicMainForm() { InitializeComponent(); } private void MainForm_Load(objectsender, EventArgs e) { LoginForm lf = newLoginForm(); lf.mainForm = this; lf.ShowDialog(); if(isLogin) { label1.Text = "load success!"; //原load事件要放到这里 } else{ this.Close(); } } } }