按照C#的编程规范,发生XXX事件的时候,通常会在OnXXX里写起实现代码,并且可以重写OnXXX来自定义控件。举例来说,微软在开发Button控件的时候,是在OnMouseMove里处理MouseMove事件的。重写如下,你可以自己试试:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Button b = new Button();
b.Location = new Point(10, 10);
b.Text = "button1";
this.Controls.Add(b);
MyButton mb = new MyButton();
mb.Location = new Point(10, 50);
mb.Text = "myButton1";
this.Controls.Add(mb);
}
}
public class MyButton : Button
{
protected override void OnMouseMove(MouseEventArgs mevent)
{
this.Text = mevent.Location.ToString();
base.OnMouseMove(mevent);
}
}
就是鼠标移动事件。