独自に作成した コンポーネントのイベントを実行する - C#

独自に作成した コンポーネントのイベントを実行するコードを紹介します。

概要

こちらの記事で作成したイベントをコンポーネントから呼び出すコードを紹介します。

UI

以下のUIを準備します。


コード

コンポーネント部 (VisualComponent.cs)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Security.Permissions;

namespace WinformVisualComponent
{
  public partial class VisualComponent : Control
  {
    public const int WM_LBUTTONDOWN = 0x00000201;
    public const int WM_RBUTTONDOWN = 0x00000204;
   
    public delegate void SimpleDelegate();
    private SimpleDelegate onSimple;

    public event SimpleDelegate OnSimple
    {
      add
      {
        //onSimple = (SimpleDelegate)Delegate.Combine(onSimple, value);
        onSimple += value;
      }
      remove
      {
        //onSimple = (SimpleDelegate)Delegate.Remove(onSimple, value);
        onSimple -= value;
      }
    }

    public VisualComponent()
    {
      InitializeComponent();
    }

    public VisualComponent(IContainer container)
    {
      container.Add(this);
      InitializeComponent();
    }

    protected override void WndProc(ref Message message)
    {
      base.WndProc(ref message);
      if (message.Msg == WM_RBUTTONDOWN) {
        if (onSimple != null) {
          onSimple();
        }
      }
    }
  }
}

解説 (コンポーネント部)

独自イベントの追加コードについてはこちらの記事を参照してください。

  protected override void WndProc(ref Message message)
  {
    base.WndProc(ref message);
    if (message.Msg == WM_RBUTTONDOWN) {
      if (onSimple != null) {
        onSimple();
      }
    }
  }
にて、WndProcメソッドをオーバーライドしてウィンドウメッセージを処理します。ウィンドウメッセージがWM_RBUTTONDOWNの場合はOnSimpleイベントを呼び出します。
アプリケーション部(SubForm.cs)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WinformVisualComponent
{
  public partial class SubFormSimple : Form
  {
    public SubFormSimple()
    {
      InitializeComponent();
    }

    private void visualComponent1_OnSimple()
    {
      textBox1.Text = "onSimple";
    }
  }
}

解説 (アプリケーション側)

コンポーネント内でマウスの右ボタンがクリックされるとOnSimpleイベントが呼び出されます。OnSimpleイベントが呼び出されるとアプリケーション側ではtextBox1にメッセージテキストを表示します。

実行結果

アプリケーションを実行すると下図のウィンドウが表示されます。


コントロール上でマウスの右ボタンをクリックするとOnSimpleイベントが呼び出されテキストボックスに文字が表示されます。


著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
最終更新日: 2024-01-07
作成日: 2011-11-16
iPentec all rights reserverd.