いろいろ備忘録日記

主に .NET とか Go とか Flutter とか Python絡みのメモを公開しています。

.NET クラスライブラリ探訪-016 (System.Windows.Forms.NativeWindow) (WndProcオーバーライド, メッセージ)


以下のすばらしい記事から今日はじめてこのクラスを知りました。


このクラスの説明はMSDNの方が詳しく乗ってますのでそちらを見た方がいいかもw

こんなのあるとは・・・・。やっぱりちゃんとクラスライブラリを見てないと駄目ですね。


これを使うと、通常if文だらけとかによくなってしまうWndProcの記述が凄くすっきりします。
さらに、今までカスタムコントロールを作成しないと処理がかけなかったのが、継承しなくても
書けるようになります。


以下、サンプルです。

// vim:set ts=4 sw=4 et ws is nowrap ft=cs:
using System;
using System.Windows.Forms;

namespace Gsf.Demo{

    public class DemoForm : Form{

        TextBox      txtBox1;
        NativeWindow _formNativeWindow;
        NativeWindow _txtBoxNativeWindow;

        public DemoForm(){
            InitializeComponent();

            _formNativeWindow   = new DemoNativeWindow(this,    "Form");
            _txtBoxNativeWindow = new DemoNativeWindow(txtBox1, "TxtBox");
        }

        protected void InitializeComponent(){
            SuspendLayout();

            txtBox1 = new TextBox{Name = "txtBox1", Text = "hoge"};

            Controls.Add(txtBox1);

            ResumeLayout();
        }

        [STAThread]
        static void Main(){
            Application.EnableVisualStyles();
            Application.Run(new DemoForm());
        }
    }

    public class DemoNativeWindow : NativeWindow{

        string  _prefix;
        Control _parent;

        public DemoNativeWindow(Control parent, string prefix){
            _parent = parent;
            _prefix = prefix;

            InitializeEventSettings();
        }

        protected void InitializeEventSettings(){
            _parent.HandleCreated   += (s, e) => {
                AssignHandle((s as Control).Handle);
            };

            _parent.HandleDestroyed += (s, e) => {
                ReleaseHandle();
            };
        }

        protected override void WndProc(ref Message m){
            Console.WriteLine(string.Format("{0}:{1}", _prefix, m.Msg));
            base.WndProc(ref m);
        }
    }

}


上記のサンプルを実行すると、フォーム側では特にWndProcをオーバーライドしていないのに
ログが表示されます。同様にフォームに配置しているテキストボックスにもWndProcを実装していないのに
ログが表示されるようになります。


追記)tekkさんも同じ内容で記事書かれてました。こちらの方が濃い内容になっています。

================================
過去の記事については、以下のページからご参照下さい。

サンプルコードは、以下の場所で公開しています。