如何使一个事件处理程序适用于C#中的多个控件?

时间:2012-05-24 14:31:24

标签: c# controls

在Visual Basic中我知道怎么做,但我是C#的新手,所以你们能告诉我如何使用鼠标悬停将“同一事件”应用于多个控件?有一个例子:

private void button1, button2, button3, button4_MouseHover(object sender, EventArgs e)
{
     btn.Image = pic
}

3 个答案:

答案 0 :(得分:12)

只需声明一个事件处理程序并将每个按钮指向它:

private void Common_MouseHover(object sender, EventArgs e)
{
     Button btn = sender as Button;
     if (btn != null)
         btn.Image = pic
}

然后在代码或设计师中:

button1.MouseHover += Common_MouseHover;
button2.MouseHover += Common_MouseHover;
.. etc

答案 1 :(得分:3)

当您在按钮上订阅该事件时,它只是一个标准的事件处理程序:

button1.Click += myEventHandler;

您可以使用相同的代码为每个按钮添加处理程序:

button1.Click += myEventHandler;
button2.Click += myEventHandler;
button3.Click += myEventHandler;
button4.Click += myEventHandler;
button5.Click += myEventHandler;
button6.Click += myEventHandler;

答案 2 :(得分:0)

button1.MouseOver += OnMouseOver(...)
button2.MouseOver += OnMouseOver(...)
button3.MouseOver += OnMouseOver(...)
button4.MouseOver += OnMouseOver(...)