C#winforms - 找到哪个控件专注于LostFocus事件

时间:2013-06-07 05:25:22

标签: c# .net winforms

我正在开发一款可在带触摸屏的标准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被添加到10个按钮,表示从0到9的数字 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;
    }

1 个答案:

答案 0 :(得分:2)

除了按钮和文本框之外,你可以简单地获得有针对性的控制,然后执行你的条件

找到聚焦控件尝试下面的代码。

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