的WinForms:如何附加一个事件处理程序附加控制 [英] Winforms: How to attach an event handler to additional controls

查看:120
本文介绍了的WinForms:如何附加一个事件处理程序附加控制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何附上相同的事件处理程序中的WinForms额外的控制/ .NET / C#?

How do i attach the same event handler to additional controls in Winforms/.NET/C#?

我的任意试图完全合乎逻辑的code来完成我想要的,但遗憾的是语法无效在C#:<​​/ P>

i randomly tried perfectly logical code to accomplish what i want, but unfortunately the syntax is not valid in C#:

public MainForm()
{
   InitializeComponent();

   FixPanelMouseEnter(pnlActionCenter);
   FixPanelMouseEnter(pnlAdministrativeTools);
   FixPanelMouseEnter(pnlAutoPlay);
   FixPanelMouseEnter(pnlBackupAndRestore);
   //...snip 49 lines...
   FixPanelMouseEnter(pnlWFirewall);
   FixPanelMouseEnter(pnlWLiveLanguageSettings);
   FixPanelMouseEnter(pnlWUpdate);
}

private void FixPanelMouseEnter(Panel panel)
{
    foreach (Control ctrl in panel.Controls)
        ctrl.MouseEnter += panel.MouseEnter;
}

本的无效的code使在语法错误

This invalid code causes the syntax error:

事件System.Windows.Forms.MouseEnter只能出现在左侧A + =或 - =

The event 'System.Windows.Forms.MouseEnter' can only appear on the left hand side of a += or -=

在这个例子中,我想小组的MouseEnter 触发事件,如果鼠标输入是在面板中的任何控制权。

In this example i want the Panel's MouseEnter event to fire if the mouse enter's any control in the panel.

<一个href="http://stackoverflow.com/questions/8173583/winforms-how-to-attach-same-event-handler-to-additional-controls">How做我附上相同的事件处理程序中的WinForms额外的控制/ .NET / C#?

在code我想不会编译。

The code i tried doesn't compile.

  • <一个href="http://stackoverflow.com/questions/8172535/winforms-how-to-cause-mouseenter-to-fire-when-the-mouse-enters-a-control">WinForms:如何引起的MouseEnter火灾当鼠标进入控制?
  • <一个href="http://stackoverflow.com/questions/8159534/net-how-to-check-if-the-mouse-is-in-a-control">.NET:如何检查鼠标是否在控制?
  • WinForms: How to cause MouseEnter to fire when the mouse enters a control?
  • .NET: How to check if the mouse is in a control?

推荐答案

修改

ctrl.MouseEnter += panel.MouseEnter;

ctrl.MouseEnter += panel_MouseEnter;

假设方法无效panel_MouseEnter 已经存在于你的code。

Assuming the method void panel_MouseEnter already exists in your code.

我认为你需要再通过事件处理程序,太:

I think you need to then pass the EventHandler, too:

private void FixPanelMouseEnter(Panel panel, EventHandler enterMethod) {
  foreach (Control ctrl in panel.Controls)
    ctrl.MouseEnter += enterMethod;
}

,然后从code:

and then from your code:

FixPanelMouseEnter(pnlActionCenter, pnlActionCenter_MouseEnter);

但同样,pnlActionCenter_MouseEnter必须已经存在。有意义吗?

But again, the pnlActionCenter_MouseEnter must already exist. Make sense?

这篇关于的WinForms:如何附加一个事件处理程序附加控制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆