C# .NET Compact Framework, custom UserControl, focus issue

会有一股神秘感。 提交于 2019-12-04 18:41:59

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.

Edit: 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!
}

It's normal that your panel doesn't receive any focus. What you can try is to look if any children of your usercontrol contains the focus. Something like this:

bool ContainsFocus(Control lookAtMe) {
 if (lookAtMe.Focused) return true;
 else {
     foreach (Control c in lookAtMe.Controls) {
         if (c.Focused) return true;
     }
 }
 return false;
}

You could also traverse them recursively if that's needed, but I don't think that's one of your requirements here.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!