如何使适用于多个控件在C#中一个事件处理程序?(How make one event handler

2019-06-24 18:29发布

在Visual Basic中,我知道该怎么做,但我是新的C#,所以你们可以告诉我,我该怎么做一个“私人无效”与应用相同的事件,多个控件鼠标悬停? 这里有一个例子:

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

Answer 1:

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

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


Answer 2:

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

button1.Click += myEventHandler;

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

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


Answer 3:

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


文章来源: How make one event handler that applies to multiple controls in C#?
标签: c# controls