我目前陷入C#.net控制组件焦点的困境。我的目标是在“点击”另一个组件(例如文本框B或其他东西)时防止丢失文本框A的焦点。除了单击文本框C或D ...之外,将保留此“焦点”机制。
这可能听起来很奇怪,但我的情况是,A,C,D行中的每一行都是一个datarepeater项目,我只想垂直移动“焦点”在右列,而不是B列。
所以,有可能在C#中做到这一点,或者我必须找到另一个控件(不是数据转发器)。任何帮助都会很感激。
答案 0 :(得分:0)
您可以使用TextBoxA的Leave事件以及包含允许获取焦点的控件的列表。
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.Winapi)]
internal static extern IntPtr GetFocus();
private Control GetFocusedControl()
{
Control focusedControl = null;
// To get hold of the focused control:
IntPtr focusedHandle = GetFocus();
if (focusedHandle != IntPtr.Zero)
// Note that if the focused Control is not a .Net control, then this will return null.
focusedControl = Control.FromHandle(focusedHandle);
return focusedControl;
}
private void textBox3_Leave(object sender, EventArgs e)
{
//Any control that is allowed to acquire focus is just added to this array.
Control[] allowedToAcquireFocusControls = {
textBox1
};
Control focusedControl = GetFocusedControl();
if (!allowedToAcquireFocusControls.Contains(focusedControl))
{
textBox3.Focus();
}
}
参考:What is the preferred way to find focused control in WinForms app?