0
1

More than 5 years have passed since last update.

C# 自前でイベントハンドラを作って使う一番簡単な例

Posted at

C# 自前でイベントハンドラを作って使う一番簡単な例

コードは以下にあります。
https://github.com/kumokumocc/WORK_/tree/master/EventTest

フォームアプリケーションで、ボタンが1個だけあります。
ボタンをクリックすると、Testというクラスをインスタンス生成し、Runというメソッドを呼び出します。
その中で5秒ウェイトしてイベントOnTestを実行します。
イベント発生すると、FoirmクラスのTestHandlerが呼び出され、"イベントハンドラが呼び出されました"というメッセージボックスを表示します。

TestクラスとForm1クラスを全く別の人が作る場合を考えると、イベントの意味が分かります。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace EventTest
{
    public class Test
    {
        public void Run()
        {
            System.Threading.Thread.Sleep(5000);//5秒待つ
            OnTest(this,EventArgs.Empty);//イベントハンドラ呼び出し
        }
        public event EventHandler OnTest;
    }

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Test t = new Test();
            t.OnTest += TestHandler;//イベントハンドラ追加
            t.Run();//実行
        }

        private void TestHandler(object sender,EventArgs e)
        {
            MessageBox.Show("イベントハンドラが呼び出されました");
        }
    }
}
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1