父窗体与子窗体实例。
设计一个登陆窗体及一个MDI窗体。
(1)登录窗体:假设密码为“123456”,密码正确,则打开一个MDI窗体,否则给出错误提示。
(2)假设MDI主窗体MDIFrm的菜单中包含一个标题为“窗口”的菜单命令。MDI窗体及空间的属性如下图:
代码:
Program.cs :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace WindowsFormsApplication3
{
static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
LoginFrm loginFrm = new LoginFrm();
loginFrm.ShowDialog();
if (loginFrm.DialogResult == DialogResult.OK)
Application.Run(new MDIFrm());//指定启动窗体
}
}
}
From1.cs (登录窗体):
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication3
{
public partial class LoginFrm : Form
{
public LoginFrm()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void btOK_Click(object sender, EventArgs e) //登录窗体,“确定”按钮代码
{
if (txtPsw.Text == "123456")
this.DialogResult = DialogResult.OK;
else
{
DialogResult dr = MessageBox.Show("密码错误", "密码验证", MessageBoxButtons.RetryCancel, MessageBoxIcon.Question);
if (dr == DialogResult.Retry)
{
txtPsw.Text = "";
txtPsw.Focus();
}
}
}
}
}
Form2.cs (MDI窗体) :
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication3
{
public partial class MDIFrm : Form
{
public MDIFrm()
{
InitializeComponent();
}
private void MDIFrm_Load(object sender, EventArgs e)
{
}
private void 子窗口1ToolStripMenuItem_Click(object sender, EventArgs e)
{
Form3 f3 = new Form3();
f3.MdiParent = this;
f3.Show();
}
private void 子窗口2ToolStripMenuItem_Click(object sender, EventArgs e)
{
Form4 f4 = new Form4();
f4.MdiParent = this;
f4.Show();
}
private void 水平排列ToolStripMenuItem_Click(object sender, EventArgs e)
{
this.LayoutMdi(MdiLayout.TileHorizontal); //水平排列
}
private void 垂直排列ToolStripMenuItem_Click(object sender, EventArgs e)
{
this.LayoutMdi(MdiLayout.TileVertical); //垂直排列
}
}
}
设计:
运行结果:
运行后,
当密码输入为“123456”,并点击确定;进入后点击“窗体菜单—子窗体1—子窗体2—垂直排列”,运行结果如下: