c# winforms -查找在LostFocus事件中关注的控件

本文关键字:控件 事件 LostFocus winforms 查找 | 更新日期: 2023-09-27 18:17:23

我正在开发一个应用程序,可以在标准pc和触摸屏pc上运行。该应用程序有许多用于数值的输入框。因此,我在GIU中添加了一个数字键盘。

我使用下面的代码将键盘链接到选定的文本框,这工作得相对较好。然而,应用程序有几个选项卡部分,我想设置这一点。如果焦点被不属于键盘或数值输入框集的任何其他控件占用,则将currentControlWithFocus设置为null。这将有助于避免偶然的键盘按下,这将导致更新由currentControlWithFocus引用的最后一个数字输入框。

我也愿意接受任何关于实现屏幕键盘的更好方法的建议。

    /// <summary>
    /// Store current control that has focus.
    /// This object will be used by the keypad to determin which textbox to update.
    /// </summary>
    private Control currentControlWithFocus = null;
    private void EventHandler_GotFocus(object sender, EventArgs e)
    {
        ((TextBox)sender).BackColor = Color.Yellow;
        this.currentControlWithFocus = (Control)sender;
    }
    private void EventHandler_LostFocus(object sender, EventArgs e)
    {
        ((TextBox)sender).BackColor = Color.White;
    }
    /// <summary>
    /// Append button's text which represent a number ranging between 0 and 9
    /// </summary>
    private void buttonKeypad_Click(object sender, EventArgs e)
    {
        if (this.currentControlWithFocus != null)
        {
            this.currentControlWithFocus.Text += ((Button)sender).Text;
            this.currentControlWithFocus.Focus();
        }
    }
    /// <summary>
    /// Removes last char from a textbox
    /// </summary>
    private void buttonKeypad_bckspc_Click(object sender, EventArgs e)
    {
        if (this.currentControlWithFocus != null)
        {
            string text = this.currentControlWithFocus.Text;
            // remove last char if the text is not empty
            if (text.Length > 0)
            {
                text = text.Remove(text.Length - 1);
                this.currentControlWithFocus.Text = text;
            }
            this.currentControlWithFocus.Focus();
        }
    }

EventHandler_LostFocus和EventHandler_GotFocus被添加到大约20个左右的输入框。buttonKeypad_Click被添加到表示数字从0到9和的10个按钮中buttonKeypad_bckspc_Click被添加到退格按钮

如果我能确定哪个控件把焦点从输入框上移开了,我就喜欢这样做。

    private void EventHandler_LostFocus(object sender, EventArgs e)
    {
        // IF NEW CONTROL WITH FOCUS IS NOT ONE OF KEYPAD BUTTONS
        //   THEN 
              ((TextBox)sender).BackColor = Color.White;
              this.currentControlWithFocus = null;
    }

c# winforms -查找在LostFocus事件中关注的控件

除了在按钮和文本框周围播放之外你可以简单地获得焦点控件然后执行你的条件

查找焦点控件,请尝试下面的代码。

public static Control FindFocusedControl(Control control)
{
    var container = control as ContainerControl;
    while (container != null)
    {
        control = container.ActiveControl;
        container = control as ContainerControl;
    }
    return control;
}