何となく Blog by Jitta
Microsoft .NET 考

目次

Blog 利用状況
  • 投稿数 - 761
  • 記事 - 18
  • コメント - 35955
  • トラックバック - 222
ニュース
  • IE7以前では、表示がおかしい。div の解釈に問題があるようだ。
    IE8の場合は、「互換」表示を OFF にしてください。
  • 検索エンジンで来られた方へ:
    お望みの情報は見つかりましたか? よろしければ、コメント欄にどのような情報を探していたのか、ご記入ください。
It's ME!
  • はなおか じった
  • 世界遺産の近くに住んでます。
  • Microsoft MVP for Visual Developer ASP/ASP.NET 10, 2004 - 9, 2011
広告

記事カテゴリ

書庫

日記カテゴリ

ギャラリ

その他

わんくま同盟

同郷

 

背景

掲示板にて、Windows アプリケーションにおいて、親子関係にある複数のフォームを表示したり、親子のフォーム間でデータを受け渡しするためにはどうすればよいか、という質問を散見するため、サンプルを提供します。

ここで提示する方法は、解決方法の一案であり、絶対的な方法ではありません。また、私自身、今回提供するサンプル コードに「これはまずい」と思っていることがあります。しかし、その場所については触れません。どこが、なぜまずいのか、考えてみてください。

前提条件

  • .NET Framework 2.0
  • C#
  • Windows Application

キーワード

  • 複数のフォーム 複数のウインドウ
  • 親子のウインドウ
  • データを渡す

提供するサンプル

  • 子フォームが、1つだけ表示されるパターン
  • 複数の子フォームが表示できるパターン1(すべて制御する)
    コンボボックスにインスタンスを表示し、制御します。また、子フォームのテキストボックスに入力した値が、親フォームに表示されます。
  • 複数の子フォームが表示できるパターン2(制御しない)
  • 上記3つのパターンで、親フォームのテキストボックスの値を、子フォームで表示します

コードと説明

まず、子フォームをひとつだけ表示するパターンです。

このパターンを実現するためには、「1アプリケーションで、ひとつだけ new する」ことを実現できれば、目的を達成できます。しかし、ここで止まってはいけません。そのたったひとつの new したフォームが、閉じてしまったらどうしましょう?つまり、「閉じた」ことを知る必要があります。

インスタンスにスコープを持つ変数に、たったひとつのインスタンスを保存します。その変数が null でなければ new し、null であればフォーカスを移します。

また、インスタンスを作成したときに、FormClosed イベントを受けるようにします。これによって、フォームが閉じたことを知り、変数を null にして、次の回にインスタンスを作成できるようにします。


#region 一つだけ表示し、消去する
/// <summary>
/// 一つだけ表示するためのインスタンスを憶える
/// </summary>
private FrmMonoInstance oneFormeInstance = null;
/// <summary>
/// 一つだけ表示
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, EventArgs e) {
    if (this.oneFormeInstance == null) {
        // インスタンスがないなら作成する
        this.oneFormeInstance = new FrmMonoInstance();
        // 向こうで閉じられた時用に、FormClosed イベントを受け取る
        this.oneFormeInstance.FormClosed += new FormClosedEventHandler(FrmMonoInstance_FormClosed);
        // 表示する
        this.oneFormeInstance.Show(this.textBox1.Text);
    } else {
        this.oneFormeInstance.Focus();
    }
}
/// <summary>
/// フォーム側で閉じられたときは、こちらで記録しているインスタンス情報を削除する
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void FrmMonoInstance_FormClosed(object sender, FormClosedEventArgs e) {
    this.oneFormeInstance = null;
}
/// <summary>
/// 一つだけ表示したものを消去
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button3_Click(object sender, EventArgs e) {
    if (this.oneFormeInstance != null) {
        this.oneFormeInstance.Close();
    }
}
#endregion

親から子へ、データを引き継ぐ方法です。

今回は、一番単純な方法をとりました。引数をひとつ受け取る Show メソッドのオーバーロードを作成して、ここで文字列を渡します。


/// <summary>
/// 表示する文字を指定して、フォームを表示する
/// </summary>
/// <param name="text"></param>
public void Show(string text) {
    this.label2.Text = text;
    this.Show();
}


次に、複数表示する場合です。この場合、開くことが出来るフォームの数に上限を決めるなら配列、上限を設けない(リソース上の上限まで)ならリストに、インスタンスを格納します。

同じように、FormClosed イベントを処理して、配列/リスト中から該当するインスタンスを削除します。

今回は、「1秒間に複数枚開くことは出来ないだろう」という甘い予想の元、DateTime.Now の値を識別子として利用します。

まず、データバインド用のクラスを作成ます。このクラスは、単体と、リストの2つを用意します。


class MultiInstanceData : IComparable<MultiInstanceData> {
    private FrmMultiInstance instance;
    /// <summary>
    /// 格納している FrmMultiInstance クラスのインスタンス
    /// </summary>
    public FrmMultiInstance Instance {
        get { return this.instance; }
    }
    /// <summary>
    /// 格納しているインスタンスの識別子
    /// </summary>
    public string Identifier {
        get {
            if (this.instance != null) {
                return this.instance.Identifier.ToString("G");
            } else {
                return string.Empty;
            }
        }
    }
    public MultiInstanceData() {
        this.instance = null;
    }
    public MultiInstanceData(FrmMultiInstance form) {
        this.instance = form;
    }
    public override bool Equals(object obj) {
        MultiInstanceData dist = obj as MultiInstanceData;
        if (dist == null) {
            return base.Equals(obj);
        } else {
            return (this.CompareTo(dist) == 0 ? true : false);
        }
    }
    public override int GetHashCode() {
        return this.Identifier.GetHashCode();
    }
    #region IComparable<MultiInstanceData> メンバ
    public int CompareTo(MultiInstanceData other) {
        return this.Identifier.CompareTo(other.Identifier);
    }
    #endregion
}

/// <summary>
/// MultiInstanceData のリスト
/// </summary>
/// <remarks>オブジェクト データ ソースとして登録できるように、殻だけ宣言</remarks>
class MultiInstanceDataList : List<MultiInstanceData> {
    public MultiInstanceDataList()
        : base() {
    }
}

さて、次にちょっとやっかいなのが、データバインドです。バインドしているデータソースに、勝手にデータを追加してはいけません。BindingSource.AddNew によって、追加します。そして、追加するデータソースを変更するには、AddingNew イベントにて、e.NewObject を操作します。

そのためには、追加するデータ クラスは、引数のない規定のコンストラクタが公開されてなければなりません。そして、様々なプロパティは、あとから変更可能でなければなりません。

という制約を無視するため、ここでは e.NewObject のインスタンスを直接置き換えるということをしています。

サンプル プロジェクト

このサンプルは、あくまで「この様な感じでコーディングすれば、目的のことが出来る」という指針です。コードの1行1行が何をしているのか、なぜ目的の動作になるのか、理解しようと努めない人が使用することを禁じます。

サンプル プロジェクトをダウンロードする

投稿日時 : 2006年12月31日 21:25
コメント
  • # .NET2.0 用、マルチ Windows Form のサンプル プロジェクト
    何となく Blog by Jitta
    Posted @ 2006/12/31 21:27
    .NET2.0 用、マルチ Windows Form のサンプル プロジェクト
  • # 複数のフォーム間で、データをやりとりする
    何となく Blog by Jitta
    Posted @ 2007/01/03 9:16
    複数のフォーム間で、データをやりとりする
  • # re: .NET 2.0 / Windows Form / マルチ ウィンドウズ フォーム
    通りすがり
    Posted @ 2007/02/28 18:33
    このようなサンプルありがとうございます。

    ですが、実行の仕方がいまいちわかりません。

    実行ファイルはどれを開いて実行すればよろしいのでしょうか?
  • # re: .NET 2.0 / Windows Form / マルチ ウィンドウズ フォーム
    Jitta
    Posted @ 2007/03/01 21:32
    通りすがりさん、コメントありがとうございます。

     「サンプルプロジェクトをダウンロードする」をクリックすると、zip ファイルがダウンロードできたと思います。これを解凍すると、ソリューションとプロジェクトがいくつか出来ます。
     とりあえずソリューションを VS2005 で読み込み、ビルドしてください。そうすると、MultiFormSample.exe が出来ます。こいつを実行してください。
  • # re: .NET 2.0 / Windows Form / マルチ ウィンドウズ フォーム
    勉強させてもらってます
    Posted @ 2009/12/02 15:05
    >「これはまずい」

    点ですが、スレッド同期周りでしょうか。
  • # ELWaeQRhFBrZqzJnW
    http://crorkz.com/
    Posted @ 2014/07/19 1:14
    wT5URr Enjoyed every bit of your post. Will read on...
  • # gPZgvUBhYc
    http://www.janetnevins.com
    Posted @ 2014/09/08 21:14
    whoah this blog is great i really like studying your posts. Keep up the great paintings! You already know, lots of persons are searching round for this information, you can aid them greatly.
  • # HgfQVWOMUCDa
    http://www.arrasproperties.com/4009-e-3rd-st-apt-3
    Posted @ 2014/09/09 19:55
    You need to take part in a contest for top-of-the-line blogs on the web. I'll suggest this site!
  • # vgtbaAITjCpW
    http://www.canadanobis.com
    Posted @ 2014/09/10 21:17
    Thanks for some other great post. Where else could anybody get that kind of info in such a perfect means of writing? I've a presentation subsequent week, and I am on the search for such info.
  • # CeYTauTPFFE
    http://www.autoaffiliatex.com/secretaccess.php?a_a
    Posted @ 2014/09/18 1:39
    I loved your article. Much obliged.
  • # UYWexzdvqMKFQtOCBXa
    http://www.youtube.com/watch?v=xIl35cOJb9A
    Posted @ 2014/09/18 20:17
    This website is really a walk-by way of for all the information you wanted about this and didn't know who to ask. Glimpse right here, and you'll undoubtedly uncover it.
  • # With havin so much content and articles do you ever run into any problems of plagorism or copyright violation? My site has a lot of completely unique content I've either created myself or outsourced but it looks like a lot of it is popping it up all ov
    With havin so much content and articles do you ev
    Posted @ 2018/09/27 3:13
    With havin so much content and articles do you ever run into any problems of
    plagorism or copyright violation? My site has a lot of completely
    unique content I've either created myself or outsourced but it looks like a lot of it is popping it
    up all over the internet without my authorization. Do you know any methods to help stop content from being stolen? I'd genuinely appreciate it.
  • # I enjoy reading through an article that can make men and women think. Also, thanks for allowing for me to comment!
    I enjoy reading through an article that can make
    Posted @ 2018/10/07 1:52
    I enjoy reading through an article that can make men and women think.

    Also, thanks for allowing for me to comment!
  • # I am regular visitor, how are you everybody? This paragraph posted at this web site is in fact good.
    I am regular visitor, how are you everybody? This
    Posted @ 2018/11/17 17:12
    I am regular visitor, how are you everybody?
    This paragraph posted at this web site is in fact good.
  • # Sling tv coupons and promo codes for november 2018 Excellent goods from you, man. I've remember your stuff prior to and you are simply extremely fantastic. I actually like what you have obtained here, certainly like what you're stating and the way in w
    Sling tv coupons and promo codes for november 2018
    Posted @ 2018/11/17 20:46
    Sling tv coupons and promo codes for november 2018
    Excellent goods from you, man. I've remember your stuff
    prior to and you are simply extremely fantastic. I actually like what you
    have obtained here, certainly like what you're
    stating and the way in which wherein you are saying it. You're making it entertaining and you continue to care
    for to stay it smart. I cant wait to read
    far more from you. This is actually a wonderful web
    site. Sling tv coupons and promo codes for november 2018
  • # You've made some good points there. I checked on the web for additional information about the issue and found most people will go along with your views on this website.
    You've made some good points there. I checked on
    Posted @ 2018/11/19 3:11
    You've made some good points there. I checked on the web for additional information about the issue and found most people will go along with your views
    on this website.
  • # This is really attention-grabbing, You are an excessively skilled blogger. I've joined your feed and sit up for seeking more of your great post. Additionally, I have shared your web site in my social networks
    This is really attention-grabbing, You are an exce
    Posted @ 2018/11/22 0:11
    This is really attention-grabbing, You are an excessively skilled blogger.
    I've joined your feed and sit up for seeking more of your great post.

    Additionally, I have shared your web site in my social networks
  • # UFUjqWBPInOsnKz
    https://www.suba.me/
    Posted @ 2018/12/17 8:37
    8XoPL8 Thanks-a-mundo for the blog article. Awesome.
  • # dVmrvNkgfAWdetb
    https://www.suba.me/
    Posted @ 2018/12/19 23:55
    y6ZOgE It as remarkable to go to see this website and reading the views of all friends
  • # IeAohEWGunAUT
    https://www.blogger.com/profile/060647091882378654
    Posted @ 2021/07/03 4:41
    This page definitely has all of the information I needed concerning this subject and didn at know who to ask.
  • # re: .NET 2.0 / Windows Form / ?????????? ????
    hydroxychlor tab 200mg
    Posted @ 2021/08/07 21:32
    hloroquine https://chloroquineorigin.com/# hydroxychloroquine 200mg
  • # nkuulxrssxct
    tnyafphs
    Posted @ 2022/06/01 10:15
    http://erythromycinn.com/# erythromycin brand name
タイトル
名前
Url
コメント