【发布时间】:2013-06-07 05:25:22
【问题描述】:
我正在开发一个可以在标准 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;
}
【问题讨论】:
-
我不认为你可以在 Lost_Focus 事件中检查这个,GotFocus 之后会被提升,我认为这是你必须检查的地方。可能在每个可能获得焦点的控件中。
-
永远不要在 winforms 中使用 Got/LostFocus,始终使用 Enter 和 Leave。您可以简单地在 Leave 事件处理程序中使用 this.ActiveControl 来获取对获得焦点的控件的引用。
-
谢谢汉斯。用 Enter 和 Leave 替换 Got/LostFocus 正是我想要的。