防止在文本框中失去焦点

Prevent losing Focus in Textbox

我目前无法控制 C#.net 中的组件焦点。我的目标是防止在 "click" 到另一个组件(例如文本框 B 或其他东西)时失去文本框 A 的焦点。此 "focus" 机制将保留,除非单击文本框 C 或 D ...。

这听起来可能很奇怪,但我的情况是 A、C、D 行中的每一行都是一个数据转发器项,我只想在右列而不是 B 列上垂直移动 "focus"。

因此,可以在 C# 中执行此操作,否则我必须找到另一个控件(不是数据转发器)。任何帮助将不胜感激。

您可以使用 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?