处理一个点击查看所有控件在窗体上 [英] Handling a Click for all controls on a Form

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

问题描述

我有一个.net用户控件(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天全站免登陆