1

我正在开发一个可以在标准 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 被添加到退格按钮

如果我可以确定哪个 Control 将焦点从输入框移开,这就是我喜欢做的事情。

    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;
    }
4

1 回答 1

2

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

找到重点控制尝试下面的代码。

public static Control FindFocusedControl(Control control)
{
    var container = control as ContainerControl;
    while (container != null)
    {
        control = container.ActiveControl;
        container = control as ContainerControl;
    }
    return control;
}
于 2013-06-07T05:42:44.627 回答