モードレスなダイアログボックスが複数表示されてしまうと困ったことになる場合が多いのではないでしょうか。。
この場合、ベースとなるWindowでダイアログボックスをすでに表示しているかどうかといった判断をさせることも可能ですが、中には複数のWindowから同じダイアログボックスを利用したいといった場合もあるでしょう。
こういったときにはシングルトンパターンと呼ばれるパターンを利用しましょう
-------------------------------------------------------
using System;
using System.Windows.Forms;
class WinSample : Form
{
private Button mybutton;
private TextBox myTextBox;
public string DispText
{
get { return this.myTextBox.Text; }
set { this.myTextBox.Text = value; }
}
public static void Main()
{
Application.Run(new WinSample());
}
public WinSample()
{
this.Text = "オーナーウィンドウ";
this.myTextBox = new TextBox();
this.myTextBox.Location = new System.Drawing.Point(100, 100);
this.Controls.Add(myTextBox);
this.mybutton = new Button();
this.mybutton.Location = new System.Drawing.Point(200, 200);
this.mybutton.Text = "子ウィンドウ";
this.mybutton.Click += new EventHandler(this.button_Click);
this.Controls.Add(mybutton);
}
private void button_Click(object sender, EventArgs e)
{
// 子ウィンドウを生成せず、インスタンスを取り出す。
WinSample2 ws2 = WinSample2.GetInstance;
ws2.Owner = this;
ws2.DispText2 = myTextBox.Text;
ws2.Show();
}
}
class WinSample2 : Form
{
private Button mybutton2;
private Button mybutton3;
private TextBox myTextBox2;
// 自分自身のインスタンスを保持するフィールド
private static WinSample2 win2=null;
// インスタンスを返すメソッド
static public WinSample2 GetInstance
{
get
{
if(win2==null)
{
// インスタンスがないときだけコンストラクタを呼ぶ
win2 = new WinSample2();
return win2;
}
else
{
return win2;
}
}
}
public string DispText2
{
set { this.myTextBox2.Text = value; }
}
// コンストラクタは自分自身以外から呼び出せないようprivateにする
private WinSample2()
{
this.Text = "子ウィンドウ";
this.myTextBox2 = new TextBox();
this.myTextBox2.Location = new System.Drawing.Point(100, 100);
this.Controls.Add(myTextBox2);
this.mybutton2 = new Button();
this.mybutton2.Location = new System.Drawing.Point(200, 180);
this.mybutton2.Text = "親から取得";
this.mybutton2.Click += new EventHandler(this.button2_Click);
this.Controls.Add(mybutton2);
this.mybutton3 = new Button();
this.mybutton3.Location = new System.Drawing.Point(200, 230);
this.mybutton3.Text = "親へ設定";
this.mybutton3.Click += new EventHandler(this.button3_Click);
this.Controls.Add(mybutton3);
}
private void button2_Click(object sender, EventArgs e)
{
this.myTextBox2.Text = ((WinSample)this.Owner).DispText;
}
private void button3_Click(object sender, EventArgs e)
{
((WinSample)this.Owner).DispText = this.myTextBox2.Text;
}
// Windowを閉じる際にインスタンスを破棄
protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
{
win2 = null;
base.OnClosing(e);
}
}
-------------------------------------------------------
コメントを記述しているあたりをじっくり眺めてみてください。
この方法だと、WinSample2のクラスのインスタンスを管理するのはWinSample2自身の仕事になり、利用するほうはインスタンスが存在しているかどうかを気にする必要がなくなります。
あおい情報システム株式会社 小野修司(どっとねっとふぁん)