处理窗体上所有控件的单击

编程入门 行业动态 更新时间:2024-10-24 22:28:58
本文介绍了处理窗体上所有控件的单击的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个 .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);

更多推荐

处理窗体上所有控件的单击

本文发布于:2023-11-09 10:14:36,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1572106.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:窗体   控件   单击

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!