問題描述
我有一個自定義 UserControl(一個標簽和一個文本框).
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.
一個小模型:Form->Panel->controls-> on keydown event (使用 KeyPreview) with a foreach 我檢查面板上有焦點的控件并使用 SelectNextControl 傳遞給下一個控件,但沒有人有焦點,因為 usercontrol 沒有獲得焦點...
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.
為我們的遞歸焦點查找函數添加了代碼:
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!
}
這篇關于C# .NET Compact Framework,自定義 UserControl,焦點問題的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!