是否有可能知道谁在焦点丢失事件中获得了焦点?
Compact Framework没有ActiveControl
,所以我不知道如何判断谁得到了关注。
答案 0 :(得分:6)
这是最终工作的解决方案:
public System.Windows.Forms.Control FindFocusedControl()
{
return FindFocusedControl(this);
}
public static System.Windows.Forms.Control FindFocusedControl(System.Windows.Forms.Control container)
{
foreach (System.Windows.Forms.Control childControl in container.Controls)
{
if (childControl.Focused)
{
return childControl;
}
}
foreach (System.Windows.Forms.Control childControl in container.Controls)
{
System.Windows.Forms.Control maybeFocusedControl = FindFocusedControl(childControl);
if (maybeFocusedControl != null)
{
return maybeFocusedControl;
}
}
return null; // Couldn't find any, darn!
}
答案 1 :(得分:2)
一个选项是互操作GetFocus API
[DllImport("coredll.dll, EntryPoint="GetFocus")]
public extern static IntPtr GetFocus();
这将为您提供当前具有输入焦点的窗口的句柄,然后您可以递归迭代控制树以查找具有该句柄的控件。
答案 2 :(得分:1)
没有。首先是一个控件的LostFocus事件然后是下一个控件的GotFocus事件。只要您无法确定用户在下一刻使用哪种控件,就不可能 而如果紧凑框架控件确实具有TabIndex属性,则只有在用户使用tab键时才能预测它。
编辑: 好的你发布了解决方案,它工作正常,我必须承认:简单的“否”是错误的 1
答案 3 :(得分:1)
使用corell.dll看起来是个好主意。
另一种可能的方法是为表单上的所有控件创建GotFocus事件处理程序然后创建一个类级别变量,该变量使用具有当前焦点的控件的名称进行更新。
答案 4 :(得分:1)
这是使用Linq
的Vaccano答案的较短代码private static Control FindFocusedControl(Control container)
{
foreach (Control childControl in container.Controls.Cast<Control>().Where(childControl => childControl.Focused)) return childControl;
return (from Control childControl in container.Controls select FindFocusedControl(childControl)).FirstOrDefault(maybeFocusedControl => maybeFocusedControl != null);
}
完全相同(在高级别的抽象中)。