在“主窗体”中使用ShowDialog()方法显示“登陆窗体”,并通过“登陆窗体”的DialogResult告知“主窗体”是否登陆成功。
1.1 主窗体:
private void FrmMain_Load(object sender, EventArgs e)
{
FrmLogin frm = new FrmLogin();
if (frm.ShowDialog() == DialogResult.OK)
{
// 执行主窗体的一些初始化内容
}
else
{
this.Close(); // 关闭主窗体
}
}
1.2 登陆窗体:
private vode btn_Login_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.OK;
}
“登陆窗体”在执行完毕后,需要将登陆用的信息传递给“主窗体”,其传递的过程就是“暂时”将用户信息存在“主窗体”可以获取的“地方”,根据“地方”不同可以有一下几种方案。
新建 User.cs
public class User {
public string username;
public User(string username)
{
this.username = username;
}
}
2.1.1 登陆窗体:
private vode btn_Login_Click(object sender, EventArgs e)
{
this.Tag = new User('rianman');
this.DialogResult = DialogResult.OK;
}
2.1.2 主窗体:
private void FrmMain_Load(object sender, EventArgs e)
{
FrmLogin frm = new FrmLogin();
if (frm.ShowDialog() == DialogResult.OK)
{
User user = frm.Tag as User; // 此处获取“登陆窗体”传递过来的数据
}
else
{
this.Close(); // 关闭主窗体
}
}
2.2.1 登陆窗体:
private vode btn_Login_Click(object sender, EventArgs e)
{
FrmMain main this.Owner as FrmMain;
main.Tag = new User("rainman");
this.DialogResult = DialogResult.OK;
}
2.2.2 主窗体:
private void FrmMain_Load(object sender, EventArgs e)
{
FrmLogin frm = new FrmLogin();
if (frm.ShowDialog() == DialogResult.OK)
{
User user = this.Tag as User; // 此处获取“登陆窗体”传递过来的数据
}
else
{
this.Close(); // 关闭主窗体
}
}
2.3.1 新建Context.cs
public class Context
{
public static User LoginUser = null;
}
2.3.2 登陆窗体:
private vode btn_Login_Click(object sender, EventArgs e)
{
Context.LoginUser = user;
this.DialogResult = DialogResult.OK;
}
2.3.3 主窗体:
private void FrmMain_Load(object sender, EventArgs e)
{
FrmLogin frm = new FrmLogin();
if (frm.ShowDialog() == DialogResult.OK)
{
User user = Context.LoginUser; // 此处获取“登陆窗体”传递过来的数据
}
else
{
this.Close(); // 关闭主窗体
}
}
2.4.1 登陆窗体:
private vode btn_Login_Click(object sender, EventArgs e)
{
FrmMain main = this.Owner as FrmMain;
main.LoginUser = new User("rainman");
this.DialogResult = DialogResult.OK;
}
2.4.2 主窗体:
public user LoginUser { get; set; }
private void FrmMain_Load(object sender, EventArgs e)
{
FrmLogin frm = new FrmLogin();
if (frm.ShowDialog() == DialogResult.OK)
{
User user = this.LoginUser; // 此处获取“登陆窗体”传递过来的数据
}
else
{
this.Close(); // 关闭主窗体
}
}