C#為控件添加自定義事件及自定義觸發(fā)
先隨便搞個事件吧
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; //點擊次數(shù)
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)
{
//觸發(fā)自定義事件
this.TestEventrg?.Invoke(this,new TestEventrgs("ming",17));//輸入的參數(shù)可以自己傳入
ClickNuM = 0;
}
}
}
}
放到界面上,狂點之后

接下來是winfrom下的已有控件,以button為例子
先添加一個組件

改為繼承 Button,并添加相應(yīng)的自定義事件
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();
}
}
}
將組件從工具箱添加到界面,添加對應(yīng)方法

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;
}
}
}
}
運行之后,狂點。觸發(fā)

到此這篇關(guān)于C#為控件添加自定義事件及自定義觸發(fā)的文章就介紹到這了,更多相關(guān)C# 控件添加自定義事件及觸發(fā)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
WPF實現(xiàn)Interaction框架的Behavior擴展
這篇文章介紹了WPF實現(xiàn)Interaction框架Behavior擴展的方法,文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-06-06
小白2分鐘學(xué)會Visual Studio如何將引用包打包到NuGet上
這篇文章主要介紹了小白2分鐘學(xué)會Visual Studio如何將引用包打包到NuGet上,只需兩步完成打包上傳操作,需要的朋友可以參考下2021-09-09
C#自定義鼠標(biāo)拖拽Drag&Drop效果之基本原理及基本實現(xiàn)代碼
拖拽效果無論是在系統(tǒng)上、應(yīng)用上、還是在網(wǎng)頁上,拖拽隨處可見,下面通過本文介紹下C#自定義鼠標(biāo)拖拽Drag&Drop效果之基本原理及基本實現(xiàn)代碼,需要的朋友可以參考下2022-04-04

