MDI子フォームを列挙する - MDI子フォームをすべて閉じる - C#
MDIアプリケーションでMDI子フォームをすべて閉じたり、MDI子フォームの情報を取得するためにMDI子フォームの一覧を取得したいことがあります。ここではMDI子フォームの列挙について紹介します。
MDI子フォームの一覧は、MDI親フォームのMdiChildrenプロパティを参照により取得できます。
UI
以下のUIを準備します
FormMain
メインフォームはIsMdiContainerプロパティをTrueに設定しMDI親フォームとします。
FormChild
MDI子フォームです。
FormOutput
情報出力用のMDI子フォームです。
コード
以下のコードを記述します。
FormMain.cs
メインフォームはLoadイベントを実装します。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace EnumMDIChildForm
{
public partial class FormMain : Form
{
public FormMain()
{
InitializeComponent();
}
private void FormMain_Load(object sender, EventArgs e)
{
FormChild fc1 = new FormChild();
fc1.MdiParent = this;
fc1.Name = "ChildForm1";
fc1.Show();
FormChild fc2 = new FormChild();
fc2.MdiParent = this;
fc2.Name = "ChildForm2";
fc2.Show();
FormChild fc3 = new FormChild();
fc3.MdiParent = this;
fc3.Name = "ChildForm3";
fc3.Show();
FormOutput fo = new FormOutput();
fo.MdiParent = this;
fo.Name = "ChildOutputForm";
fo.Show();
}
}
}
解説
LoadイベントでMDI子フォームのインスタンスを作成します。また、MDI子フォームのMdiParentにthisを設定し自身を親フォームとする設定にします。Nameプロパティを設定しフォームの判別ができるようにします。
FormOutput.cs
配置したButtonのClickイベントを実装します。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace EnumMDIChildForm
{
public partial class FormOutput : Form
{
public FormOutput()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
for (int i=0;i<this.MdiParent.MdiChildren.Length; i++){
textBox1.Text+= this.MdiParent.MdiChildren[i].Name + "\r\n";
}
}
private void button2_Click(object sender, EventArgs e)
{
foreach (Form c in this.MdiParent.MdiChildren){
c.Close();
}
}
}
}
解説
button1ではMDI親フォームのMdiChildrenプロパティを参照しMDI子フォームのNameプロパティの値をテキストボックスに表示します。button2ではMDI子フォームをすべて閉じます。
実行結果
プロジェクトを実行します。下図のウィンドウが表示されます。
button1をクリックします。MDI子フォームの名前がテキストボックスに表示されます。
button2をクリックします。MDI子フォームがすべて閉じられ下図の画面となります。
著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
最終更新日: 2024-01-06
作成日: 2012-05-20