繁体   English   中英

C#Winforms-查找哪个控件关注LostFocus事件

[英]C# winforms - find which control took focus on LostFocus event

我正在开发一个将在标准PC和带触摸屏的PC上运行的应用程序。 该应用程序具有数字输入框的数量。 因此,我向GIU添加了数字小键盘。

我使用下面的代码将小键盘链接到选定的文本框,效果相对较好。 但是,该应用程序具有几个选项卡式的节,如果要通过不属于键盘或数字输入框集的任何其他控件进行聚焦,我想将this.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;
    }

然后在按钮和文本框周围玩,您可以简单地获得焦点控制,然后执行条件

要找到Focused控件,请尝试以下代码。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM