C#為控件添加自定義事件及自定義觸發(fā)
更新時間:2022年04月29日 09:12:38 作者:Code- Sheep
C#本身提供了很強大的控件庫,但是很多控件庫的功能只是一些基本的功能,本文主要介紹了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; //點擊次數 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));//輸入的參數可以自己傳入 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; } } } }
運行之后,狂點。觸發(fā)
到此這篇關于C#為控件添加自定義事件及自定義觸發(fā)的文章就介紹到這了,更多相關C# 控件添加自定義事件及觸發(fā)內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
小白2分鐘學會Visual Studio如何將引用包打包到NuGet上
這篇文章主要介紹了小白2分鐘學會Visual Studio如何將引用包打包到NuGet上,只需兩步完成打包上傳操作,需要的朋友可以參考下2021-09-09C#自定義鼠標拖拽Drag&Drop效果之基本原理及基本實現代碼
拖拽效果無論是在系統(tǒng)上、應用上、還是在網頁上,拖拽隨處可見,下面通過本文介紹下C#自定義鼠標拖拽Drag&Drop效果之基本原理及基本實現代碼,需要的朋友可以參考下2022-04-04