最后一个焦点的文本框

时间:2011-01-19 16:47:26

标签: vb.net textbox focus

我有一个带有+ 50控件的表单,并且只有5个文本框中的键盘数字屏幕。

我正在使用此代码使用键数字屏幕在这些文本框中写入:

Private Sub bt0_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bt0.Click, bt1.Click, bt2.Click, bt3.Click, bt4.Click, bt5.Click, bt6.Click, bt7.Click, bt8.Click, bt9.Click, btDec.Click
        If TypeOf sender Is DevExpress.XtraEditors.SimpleButton Then
            txtRefe.Focus()
            SendKeys.Send(CType(sender, DevExpress.XtraEditors.SimpleButton).Text)
        End If
    End Sub

问题:在触摸数字按钮之前,我需要知道这5个文本框中的哪一个具有焦点

我已在此帖Find out the control with last focus中看到此代码,以找到最后一个焦点:

Private _focusedControl As Control
    Private Sub TextBox_GotFocus(ByVal sender As Object, ByVal e As EventArgs)
        _focusedControl = DirectCast(sender, Control)
    End Sub
    Private Sub button1_Click(ByVal sender As Object, ByVal e As EventArgs)
        If _focusedControl IsNot Nothing Then
            'Change the color of the previously-focused textbox
            _focusedControl.BackColor = Color.Red
        End If
    End Sub

但是我如何使用+ 50控件(多种类型的控件:按钮,复选框,组合,文本框等)进行操作?

2 个答案:

答案 0 :(得分:0)

您可以递归循环遍历表单的Controls集合并添加事件处理程序。

答案 1 :(得分:0)

任何人想到的最简单,最简单的解决方案是制作一个包含您选择的数据类型的标志。让我们说int,那么你要做的就是为每个textBox的每个焦点事件用不同的值更新该标志。为简单起见,

When textBox1 gets focused -> set the flag value to 1
when textBox2 gets focused -> set the flag value to 2
when textBox3 gets focused -> set the flag value to 3
when textBox4 gets focused -> set the flag value to 4
when textBox5 gets focused -> set the flag value to 5

现在,您将保留最后一个焦点文本框的记录。您可以执行switch语句来处理我们拥有的5个案例中的每一个

   Select Case flag
    case 1: 'code for textBox1
    case 2: 'code for textBox2
    case 3: 'code for textBox3
    case 4: 'code for textBox4
    case 5: 'code for textBox5
   End Select