在失去焦点事件中,是否有可能知道谁获得了焦点?
由于紧凑框架(Compact Framework)没有ActiveControl
,因此我不知道如何确定谁获得了焦点。
在失去焦点事件中,是否有可能知道谁获得了焦点?
由于紧凑框架(Compact Framework)没有ActiveControl
,因此我不知道如何确定谁获得了焦点。
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!
}
[DllImport("coredll.dll, EntryPoint="GetFocus")]
public extern static IntPtr GetFocus();
这将为您提供当前具有输入焦点的窗口句柄,然后您可以递归迭代控件树以查找具有该句柄的控件。
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);
}
不行。首先是一个控件的LostFocus事件,然后是下一个控件的GotFocus事件。只有在你无法确定用户下一步使用哪个控件时,才不可能实现。
而如果紧凑框架控件具有TabIndex属性,则仅当用户使用Tab键时才能预测。
编辑: 好的,你发布了解决方案,我必须承认它很好:简单的“不行”是错误的。 +1
使用corell.dll似乎是个不错的主意。
另一种可能的方法是为表单上的所有控件创建GotFocus事件处理程序,然后创建一个类级变量,该变量会随着当前焦点所在控件的名称而更新。