处理窗体上所有控件的单击 [英] Handling a Click for all controls on a Form

查看:21
本文介绍了处理窗体上所有控件的单击的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 .NET UserControl (FFX 3.5).该控件包含多个子控件 - 一个面板、一对标签、一对文本框和另一个自定义控件.我想在基本控件上的任何地方进行右键单击 - 因此右键单击任何子控件(或在面板的情况下是子控件的子控件).我想这样做,以便在有人更改控件时可以维护它,而不必为新控件连接处理程序.

I have a .NET UserControl (FFX 3.5). This control contains several child Controls - a Panel, a couple Labels, a couple TextBoxes, and yet another custom Control. I want to handle a right click anywhere on the base Control - so a right click on any child control (or child of a child in the case of the Panel). I'd like to do it so that it's maintainable if someone makes changes to the Control without having to wire in handlers for new Controls for example.

首先,我尝试覆盖 WndProc,但正如我所怀疑的,我只收到直接点击表单的消息,而不是它的任何子节点.作为半黑客,我在 InitializeComponent 之后添加了以下内容:

First I tried overriding the WndProc, but as I suspected, I only get messages for clicks on the Form directly, not any of its children. As a semi-hack, I added the following after InitializeComponent:

  foreach (Control c in this.Controls)
  {
    c.MouseClick += new MouseEventHandler(
      delegate(object sender, MouseEventArgs e)
      {
        // handle the click here
      });
  }

这现在获得了支持该事件的控件的点击次数,但例如,标签仍然没有获得任何东西.有没有一种简单的方法可以做到这一点,而我却忽略了这一点?

This now gets clicks for controls that support the event, but Labels, for example, still don't get anything. Is there a simple way to do this that I'm overlooking?

推荐答案

如果标签在子控件中,那么您必须递归地执行此操作:

If the labels are in a subcontrol then you'd have to do this recursively:

void initControlsRecursive(ControlCollection coll)
 { 
    foreach (Control c in coll)  
     {  
       c.MouseClick += (sender, e) => {/* handle the click here  */});  
       initControlsRecursive(c.Controls);
     }
 }

/* ... */
initControlsRecursive(Form.Controls);

这篇关于处理窗体上所有控件的单击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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