如何跟踪任何子控件在WinForms中获取或失去焦点? [英] How track when any child control gets or loses the focus in WinForms?

查看:170
本文介绍了如何跟踪任何子控件在WinForms中获取或失去焦点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Windows窗体自定义控件,就像一个面板,它可以包含任意数量的子项。子控件的数量和类型是在运行时确定的,所以我需要以通用的方式工作,而不知道可能或不可能存在的确切子控件。



我想改变我的面板的背景颜色取决于面板是否包含焦点。所以如果面板的孩子(或面板的孩子的孩子等)采取焦点,我想知道这一点,所以我可以更新自定义面板的背景颜色。当焦点转移到不在子层次结构中的东西时,我也需要知道,所以我可以恢复到原来的背景色。



Control.ContainsFocus是很好的告诉我,如果面板包含在儿童阶层的焦点,但我需要知道什么时候有变化。目前我只能拿出以下不良的机制。

我钩入每个孩子的GotFocus / LostFocus和每个孩子的每个孩子等。我也必须挂钩ControlAdded / ControlRemoved,以确保我保持与可能改变孩子hieararchy。正如你所看到的,这可能以ALOT事件挂钩结束,我怀疑必须有一个更简单的方法。任何想法?

解决方案

恐怕这是唯一的选择。有时Winforms有一些恼人的漏洞。我没有检查过,但是如果ContainsFocus只是一个容器控件的控制树的递归遍历来查看是否有任何控件有焦点,那就不会感到惊讶。

拥有大量的事件处理程序并不是什么大问题,引发了很多改变UI元素的事件。你可以通过对可添加的控件进行子类化(但我不确定是否必须允许所有控件或只是一个子集),并将面板传递给添加的控件,以便控件在调用时调用它/失去重点。但这也是一个很大的工作,在面板中的代码观察员模式是恕我直言,更容易做到。

I have a Windows Forms custom control which acts like a panel in that it can contain any number of children. The number and type of the child controls are determined at runtime and so I need to work in a generic manner without knowing the exact child controls that might or might not be present.

I want to alter the background color of my panel depending on if the panel contains the focus. So if a child of the panel (or a child of a child of the panel etc...) takes the focus I want to know this so I can update the background color of the custom panel. When the focus shifts away to something that is not in the child hierarchy then I also need to know so I can revert to the original background color.

The Control.ContainsFocus is great for telling me if the panel contains the focus in the child hierarchy but I need to know when there is a change. At the moment I can only come up with the following poor mechanism.

I hook into the GotFocus/LostFocus of each child and each child of each child etc. I also have to hook the ControlAdded/ControlRemoved to ensure I keep in sync with the possible changing child hieararchy. As you can see this might end up with ALOT of event hooks and I suspect there must be an easier approach. Any ideas?

解决方案

I'm afraid that's the only option. Winforms has some annoying holes in its api sometimes. I haven't checked but it wouldn't surprise me if ContainsFocus is simply a recursive traversal of the control tree of a container control to see if any control has the focus.

Having a lot of event handlers is not that much of a problem, raising a lot of events which change UI elements is. You could work around this by subsclassing the controls which are addable (but I'm not sure if you have to allow all controls or just a subset) and pass the panel to the control added so the control itself calls into the panel when it gets/loses focus. But that's also a lot of work and the observer-like pattern of having the code in the panel is IMHO easier to do.

这篇关于如何跟踪任何子控件在WinForms中获取或失去焦点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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