분노의 챔질

C# Event 본문

Programming/C#

C# Event

분노의블로그 2024. 5. 28. 09:31
반응형

MyEvents.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace EventsTest
{
    public class MyEvents
    {
        string returnstring = string.Empty;

        public MyEvents()
        {

        }

        public void CallEvents(string val)
        {
            if(val == "철수")
            {
                MyEventsEventArgs rev = new MyEventsEventArgs("남자", val);
                Received(rev);
            }
            else if (val == "영희")
            {
                MyEventsEventArgs rev = new MyEventsEventArgs("여자", val);
                Received(rev);
            }
            else
            {
                MyEventsEventArgs rev = new MyEventsEventArgs("종족확인불가", val);
                Received(rev);
            }
        }

        public delegate void MyEventsHandler(object sender, MyEventsEventArgs e);
        public event MyEventsHandler OnDataChange;

        protected virtual void Received(MyEventsEventArgs e)
        {
            MyEventsHandler handler = OnDataChange;

            if (handler != null)
                handler(this, e);
        }

        public class MyEventsEventArgs : EventArgs
        {
            private readonly string result;
            private readonly string value;

            public MyEventsEventArgs(string r, string v)
            {
                this.result = r;
                this.value = v;
            }

            public string _Result
            {
                get { return this.result; }
            }

            public string _Value
            {
                get { return this.value; }
            }
        }
    }
}

 

Form2.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 EventsTest
{
    public partial class Form2 : Form
    {
        MyEvents ev = new MyEvents();

        public Form2()
        {
            InitializeComponent();
        }

        private void Form2_Load(object sender, EventArgs e)
        {
            ev.OnDataChange += Ev_OnDataChange;
        }

        private void Ev_OnDataChange(object sender, MyEvents.MyEventsEventArgs e)
        {
            MessageBox.Show(e._Result + " : " + e._Value);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            ev.CallEvents("철수");
        }

        private void button2_Click(object sender, EventArgs e)
        {
            ev.CallEvents("영희");
        }

        private void button3_Click(object sender, EventArgs e)
        {
            ev.CallEvents("치와와");
        }
    }
}
반응형

'Programming > C#' 카테고리의 다른 글

C# Log파일  (0) 2024.05.28
C# delegate  (0) 2024.05.28
C# Windows Media Player 사용하기  (0) 2023.01.11
UltraGrid에서 Ctrl+C  (0) 2021.04.13
C# 키보드 마우스 후킹 HOOK  (0) 2018.07.04