C# 控件添加自定义事件及触发
Code- Sheep 人气:0先随便搞个事件吧
public class TestEventrgs : EventArgs { private string _name; public string Name { get { return _name; } } private int _age; public int Age { get { return _age; } } public TestEventrgs(string name,int age) { _name = name; _age = age; } }
分两种,自定义控件和winfrom下的已有控件
先来个自定义控件吧
随便搞个界面
上马
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace CSDN { public partial class UserControl1 : UserControl { int ClickNuM = 0; //点击次数 public event EventHandler<TestEventrgs> TestEventrg;//自定义的事件 public UserControl1() { InitializeComponent(); this.TestEventrg += new EventHandler<TestEventrgs>(DangeTip);//自定义事件绑定的方法 } private void DangeTip(object sender, TestEventrgs e) { string tool = string.Format("危险提示:{0}你小子别狂点,仗着{1}岁手速快是吧!?",e.Name,e.Age); MessageBox.Show(tool); } protected override void OnClick(EventArgs e) { base.OnClick(e); ClickNuM++; if (ClickNuM>5) { //触发自定义事件 this.TestEventrg?.Invoke(this,new TestEventrgs("ming",17));//输入的参数可以自己传入 ClickNuM = 0; } } } }
放到界面上,狂点之后
接下来是winfrom下的已有控件,以button为例子
先添加一个组件
改为继承 Button,并添加相应的自定义事件
using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace CSDN { public partial class MyButton : Button { public MyButton() { InitializeComponent(); } public event EventHandler<TestEventrgs> TestEventrg; public MyButton(IContainer container) { container.Add(this); InitializeComponent(); } } }
将组件从工具箱添加到界面,添加对应方法
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 CSDN { public partial class Form2 : Form { public Form2() { InitializeComponent(); } int ClickNuM = 0; private void myButton1_TestEventrg(object sender, TestEventrgs e) { string tool = string.Format("危险提示:{0}你小子别狂点,仗着{1}岁手速快是吧!?", e.Name, e.Age); MessageBox.Show(tool); } private void myButton1_Click(object sender, EventArgs e) { ClickNuM++; if (ClickNuM > 5) { myButton1_TestEventrg(this, new TestEventrgs("lang", 88)); ClickNuM = 0; } } } }
运行之后,狂点。触发
加载全部内容