码迷,mamicode.com
首页 > 其他好文 > 详细

事件例程

时间:2014-12-17 14:33:07      阅读:240      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   ar   io   color   os   使用   sp   

该例子演示了A窗口监听B窗口的事件,并作出响应。

B窗口是发布者,A窗口是订阅者。

B窗口代码:

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 theEvent
{
    //自定义事件参数,继承EventArgs基类
    public class myEventArgs : EventArgs
    {
        public string label;
    }

    //发布者
    public partial class FormB : Form
    {
        public FormB()
        {
            InitializeComponent();
        }

        public event EventHandler<myEventArgs> myEvent;//使用自定义泛型委托

        //由发布者来触发事件,让订阅者来响应
        private void buttonB_Click(object sender, EventArgs e)
        {
            myEventArgs args = new myEventArgs();
            args.label = "FUCK YOU!";
            if (myEvent != null)
            {
                myEvent(this, args);//引发事件
            }
            this.Close();
        }
    }
}

A窗口代码:

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 theEvent
{
    //订阅者
    public partial class FormA : Form
    {
        FormB b = null;

        public FormA()
        {
            InitializeComponent();

            b = new FormB();//实例化一个发布者的类
            //订阅该发布者的事件
            b.myEvent += myEventFunction;//监听B窗体事件
        }

        void myEventFunction(object source, myEventArgs e)
        {
            labelA.Text = e.label;
        }

        private void buttonA_Click(object sender, EventArgs e)
        {
            b.Show();
        }
    }
}

 

A窗口为主窗口。点击AAAAA按钮后弹出B窗口。点击BBBBB按钮后,触发事件,A窗口“原值”变成“FUCK YOU!”。

bubuko.com,布布扣  bubuko.com,布布扣  bubuko.com,布布扣

事件例程

标签:style   blog   http   ar   io   color   os   使用   sp   

原文地址:http://www.cnblogs.com/xieqianli/p/4169182.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!