・フォーム親子関係のウィンドウでデリゲートを使って子から親へメッセージ送信する書き方
親側クラス
public delegate void MyDelegete(string str); // これはどこかに書いておく。親中心の場合はここでOKだろう
public partial class Parent : Form {
private void Button1_Click(object sender, EventArgs e)
{
child = new Child();
child.mDelegete += Write;
FormThread.Start(child, this);
}
public void Write(string str)
{
this.textBox.Text = str;
}
}
子側クラス
public partial class Child : Form
{
public event MyDelegete mDelegete; // event をつけた場合は他のクラスからの呼び出しができなくなる
public Child()
{
InitializeComponent();
// ここでデリゲート呼び出しは無理、やったら固まる
}
private void button1_Click(object sender, EventArgs e)
{
mDelegete("子フォームからのメッセージ"); // ここでデリゲート呼び出し
}
}
(無理やりな)フォームスレッド操作クラス(このコードは一応動くが、スレッド同期上の問題がある)
using System;
using System.Windows.Forms;
using System.Threading;
namespace Program
{
class FormThread
{
static Form sForm;
public static void Start(Form form, Form parent)
{
Thread t = new Thread(new ThreadStart(FormThread.Do));
sForm = form;
parent.AddOwnedForm(form); // 親子関係を設定
t.Start();
}
private static void Do()
{
Application.Run(sForm);
}
}
}
Program.cs
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Parent());
Application.Exit(); // 一応、子フォームスレッドの片付け
}
}
・テキストボックスで全て選択ショートカットできるようにするにはここ。
・Formクラスのメンバ