モーダルなダイアログボックスを作成するサンプルです。
-------------------------------------------------------
using System;
using System.Windows.Forms;
class WinSample : Form
{
private Button mybutton;
public static void Main()
{
Application.Run(new WinSample());
}
public WinSample()
{
this.Text = "ベースウィンドウ";
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)
{
// ダイアログボックスの生成
myDialog myD = new myDialog();
// ダイアログボックスの表示と結果の取得
if(DialogResult.OK==myD.ShowDialog())
MessageBox.Show(myD.InputData);
// ダイアログボックスの破棄
myD.Dispose();
}
}
class myDialog : Form
{
private Button okButton;
private Button cancelButton;
private TextBox myTextBox;
// テキストボックス内のデータを外部から読み出すためのプロパティ
public String InputData
{
get { return myTextBox.Text; }
}
public myDialog()
{
this.Text = "ダイアログウィンドウ";
// ダイアログウィンドウらしい見映えの設定
this.MaximizeBox = false;
this.MinimizeBox = false;
this.FormBorderStyle = FormBorderStyle.FixedDialog;
this.myTextBox = new TextBox();
this.myTextBox.Location = new System.Drawing.Point(100, 100);
this.Controls.Add(myTextBox);
this.okButton = new Button();
this.okButton.Location = new System.Drawing.Point(200, 180);
this.okButton.Text = "OK";
// ボタンクリック時の戻り値の設定
this.okButton.DialogResult = DialogResult.OK;
// ウィンドウ上でEnterキーが押されたときの動作を設定
this.AcceptButton = okButton;
this.Controls.Add(okButton);
this.cancelButton = new Button();
this.cancelButton.Location = new System.Drawing.Point(200, 220);
this.cancelButton.Text = "Cancel";
this.cancelButton.DialogResult = DialogResult.Cancel;
// ウィンドウ上でEscキーが押されたときの動作を設定
this.CancelButton = cancelButton;
this.Controls.Add(cancelButton);
}
}
-------------------------------------------------------
作成したFormをShowDialogメソッドで表示させればモーダルダイアログとして動作します。
ダイアログボックス側でpublicなプロパティを作成しておけば、呼び出した側がそのデータを取り出すことができます。
上記の設定の場合、テキストボックスに入力中にEnterキーが押されるとDialogResult.OKを返します。
また、Escキーが押された場合はDialogResult.Cancelを返します。
ダイアログボックスの右上の[X]をクリックしてダイアログボックスを閉じた場合もDialogResult.Cancelが返されますので、うまく利用しましょう。
あおい情報システム株式会社 小野修司(どっとねっとふぁん)