Go homepage(回首页) Upload pictures (上传图片) Write articles (发文字帖)
The author:(作者)qqpublished in(发表于) 2014/7/11 9:18:57 C#中创建MDI应用程序
C#中创建MDI应用程序
创建MDI应用程序本节通过一个实例介绍创建MDI应用程序的具体过程及设置窗体的布局。实例运行结果如图1所示。图1 MDI应用程序运行结果程序开发步骤如下。(1)新建一个Windows应用程序,命名为07_02,默认窗体为Form1.cs。(2)将窗体Form1的IsMdiContainer属性设置为True,作为MDI父窗体,然后再添加两个Windows窗体,作为MDI子窗体。(3)在Form1窗体中,添加一个MenuStrip控件,作为该父窗体的菜单项。(4)程序主要代码如下。MDI父窗体Form1中,声明MDI子窗体Form2和Form3的两个实例对象,并给它们赋值为null,用来判断子窗体是第一次打开,还是已经加载过而被释放掉了。声明MDI子窗体Form2和Form3对象的代码如下: Form2 frmChild1 = null;Form3 frmChild2 = null;单击“打开子窗体1”菜单项时,程序首先判断“子窗体1”是否打开,如果没有,则实例化一个新的对象,并以当前窗体为父窗体进行显示,否则,判断“子窗体1”的对象是否释放。如果释放,则重新实例化一个对象;如果没有释放,则获得“子窗体1”对象的焦点。“打开子窗体1”菜单项的Click事件代码如下: private void 打开子窗体1ToolStripMenuItem_Click(object sender, EventArgs e){if (frmChild1 == null){frmChild1 = new Form2();frmChild1.MdiParent = this;frmChild1.Show();}else{if (frmChild1.IsDisposed){frmChild1 = new Form2();}frmChild1.MdiParent = this;frmChild1.Show();frmChild1.Focus();}}说明:“打开子窗体2”菜单项的Click事件与“打开子窗体1”菜单项的Click事件代码实现原理类似,其详细代码请参见本书附带光盘。单击“水平排列”菜单项时,如果父窗体中有多个子窗体,程序会将这些窗体按照一定的顺序水平排列在父窗体中。“水平排列”菜单项的Click事件代码如下: private void 水平排列ToolStripMenuItem_Click(object sender, EventArgs e){LayoutMdi(MdiLayout.TileHorizontal);}说明:“垂直排列”菜单项的Click事件与“水平排列”菜单项的Click事件代码实现原理类似,其详细代码请参见本书附带光盘。完整程序代码如下:★ ★★★★Form1.cs窗体代码文件完整程序代码★★★★★ using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;namespace _7_02{public partial class Form1 : Form{Form2 frmChild1 = null;Form3 frmChild2 = null;public Form1(){InitializeComponent();}private void 打开子窗体1ToolStripMenuItem_Click(object sender, EventArgs e){if (frmChild1 == null){frmChild1 = new Form2();frmChild1.MdiParent = this;frmChild1.Show();}else{if (frmChild1.IsDisposed){frmChild1 = new Form2();}frmChild1.MdiParent = this;frmChild1.Show();frmChild1.Focus();}}private void 打开子窗体2ToolStripMenuItem_Click(object sender, EventArgs e){if (frmChild2 == null){frmChild2 = new Form3();frmChild2.MdiParent = this;frmChild2.Show();}else{if (frmChild2.IsDisposed){frmChild2 = new Form3();}frmChild2.MdiParent = this;frmChild2.Show();frmChild2.Focus();}}private void 水平排列ToolStripMenuItem_Click(object sender, EventArgs e){LayoutMdi(MdiLayout.TileHorizontal);}private void 垂直排列ToolStripMenuItem_Click(object sender, EventArgs e){LayoutMdi(MdiLayout.TileVertical);}private void 退出ToolStripMenuItem_Click(object sender, EventArgs e){Application.Exit();}}}★ ★★★★Form1.designer.cs窗体设计文件完整程序代码★★★★★
赞