標準の 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 個の入力ボックスに追加されます。0 から 9 までの数字を表す 10 個のボタンに buttonKeypad_Click が追加され、バックスペース ボタンに buttonKeypad_backspc_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;
}