C#—MDI(多文件介面)
阿新 • • 發佈:2019-01-03
父窗體與子窗體例項。
設計一個登陸窗體及一個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—垂直排列”,執行結果如下: