C#本身提供了很强大的控件库,但是很多控件库的功能只是一些基本的功能,本文主要介绍了C#为控件添加自定义事件及自定义触发,具有一定的参考价值,感兴趣的可以了解一下
先随便搞个事件吧
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;
}
}
}
}
运行之后,狂点。触发
到此这篇关于C#为控件添加自定义事件及自定义触发的文章就介绍到这了,更多相关C# 控件添加自定义事件及触发内容请搜索得得之家以前的文章希望大家以后多多支持得得之家!
织梦狗教程
本文标题为:C#为控件添加自定义事件及自定义触发


基础教程推荐
猜你喜欢
- C# 解析XML和反序列化的示例 2023-04-14
- 实例详解C#实现http不同方法的请求 2022-12-26
- C#中 Json 序列化去掉null值的方法 2022-11-18
- c# – USING块在网站与Windows窗体中的行为不同 2023-09-20
- C#获取指定目录下某种格式文件集并备份到指定文件夹 2023-05-30
- C#调用摄像头实现拍照功能的示例代码 2023-03-09
- C#中的Linq to JSON操作详解 2023-06-08
- Unity 如何获取鼠标停留位置下的物体 2023-04-10
- Unity shader实现高斯模糊效果 2023-01-16
- C#通过标签软件Bartender的ZPL命令打印条码 2023-05-16