C#.NET Compact Framework的,定制的用户控件,焦点问题控件、焦点、用户、问题

2023-09-04 22:54:26 作者:范二先生。

我有一个自定义用户控件(标签和文本框)。

I have a custom UserControl (a label and a textbox).

我的问题是,我需要下处理键,键向上事件表单控件之间的导航(的。NET Compact Framework的的文本框,组合框等)。随着由.NET Compact Framework的框架,它的工作原理,但是当我到了我写的一个用户控件,控制不`吨获得焦点(文本框里面获得焦点),所以从这个用户控件,我不能,因为在面板上浏览所提供的控件我没有对谁拥有焦点任何控制。

My problem is I need to handle the key down, key up events to navigate between controls in the form (.NET Compact Framework textbox, combobox, etc). With the controls provided by the .NET Compact Framework framework it works, but when I reach a usercontrol written by me, that control don`t get focus (the textbox inside get the focus) so from this usercontrol I cannot navigate because in the panel I don't have any control of who have focus.

小模拟了: 形式 - >面板 - >控制 - >对keydown事件(使用密钥preVIEW)在foreach我检查什么控制具有焦点的面板上,并传递到下一个控制SelectNextControl,但没有人有焦点,因为用户控件唐`吨得到了集中...

A little mock up : Form->Panel->controls -> on keydown event (using KeyPreview) with a foreach I check what control have focus on the panel and pass to the next control with SelectNextControl, but no one have focus because the usercontrol don`t got focus...

我试图处理文本框GotFocus事件,并把重点转向用户的控制,但我得到了一个无限循环。

I tried to handle the textbox gotFocus event and put focus to the user control, but I got an infinite loop..

是否有人有任何想法,我该怎么办?

Does somebody have any idea what can I do?

推荐答案

我们已经做了上Compact Framework的完全一样的东西,将成为全球焦点管理器,它支持使用键盘输入控件之间进行导航。

We've done the exact same thing on Compact Framework, adding a global focus manager that supports navigating between controls using keyboard input.

基本上,你需要做的是递归下降控件的树,直到找到具有焦点的控制。这不是非常有效的,但只要你仅仅在每个关键事件做一次,它不应该是一个问题。

Basically, what you need to do is to recurse down the tree of controls until you find a control that has focus. It's not terribly efficient, but as long as you only do it once per key event, it shouldn't be an issue.

编辑:添加了code的递归重点查找功能:

Added the code for our recursive focus finding function:

public static Control FindFocusedControl(Control container)
{
    foreach (Control childControl in container.Controls) {
        if (childControl.Focused) {
            return childControl;
        }
    }

    foreach (Control childControl in container.Controls) {
        Control maybeFocusedControl = FindFocusedControl(childControl);
        if (maybeFocusedControl != null) {
            return maybeFocusedControl;
        }
    }

    return null; // Couldn't find any, darn!
}