winform程序登陆后关闭登录窗体

用winform做程序的时候,我们一般都是在Program先启动登录窗体,然后登录成功后才创建主窗体,结果这就导致了登录窗体无法关闭

所以如果我们不在Program的程序入口先创建登录窗体的话就能完美实现登录成功后关闭登录窗体的功能了,直接贴代码

复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MainForm()); //程序启动于主窗体,而非登录窗体
        }
    }
}
复制代码
复制代码
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;

namespace WindowsFormsApplication1
{
    public partial class LoginForm : Form
    {
        public MainForm mainForm; //获得主窗体引用,可以更新主窗体的登录标志
        public LoginForm()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (textBox1.Text == "admin")
            {
                mainForm.isLogin = true;
                this.Close(); //登陆成功则关闭登录窗体
            }
            else
            {
                MessageBox.Show("密码错误!");
            }
        }
    }
}
复制代码
复制代码
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;

namespace WindowsFormsApplication1
{
    public partial class MainForm : Form
    {
        public bool isLogin = false; //登录标志
        public MainForm()
        {
            InitializeComponent();
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            LoginForm lf = new LoginForm();
            lf.mainForm = this;
            lf.ShowDialog();
            if (isLogin)
            {
                label1.Text = "load success!"; //原load事件要放到这里
            }
            else
            {
                this.Close();
            }
        }
    }
}
复制代码

 

posted @   WmW  阅读(1836)  评论(0编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~
点击右上角即可分享
微信分享提示