文本框光标操作

时间:2014-11-04 20:44:27

标签: vb.net

我昨天找到了解决问题的方法,但我已经想出了一个新问题。

我的程序是一个多标签计算器,对于用户输入,我的目标是全键盘导航。我把我的盒子放在一个网格中,每个盒子都有一个keydown subs来捕获箭头键,允许用户使用箭头在盒子之间导航。

我发现的缺陷是,如果我在框中输入内容并犯了错误(在运行时),我要么退格x次并重新输入,要么单击光标到位以更改单个字符。我很快就发现需要使用左箭头和右箭头来导航文本框中的光标位置,但是想保留一些导航功能。

所以基于此我有几个问题。

有没有办法检测文本控件中的光标位置? 如果是这样,光标位置是否为数字?即盒子开头的位置= 0,第一和第二个字符之间的位置= 1,等等。

我正在尝试编写一个子字母来计算字符串中的字符,确定光标是在所述字符串的左侧还是右侧,然后允许适当移动到下一个框中。

Private Sub countCharacters()
  'I'm not sure of the syntax yet, I'm researching this currently, so please bear with 
  'me, I'm trying to get my concept across.

  Dim txtBoxCount As Integer
  txtBoxCount = txtBox1.Text.count '???

  Dim txtBoxPos As Integer
  txtBox1.cursor.position.get '???
End Sub

Private Sub onKeyDown()
  countCharacters()
  If e.KeyData = Keys.Left Then
     e.SuppressKeyPress = True  'As I'm typing this, I realize I might need to change this, but 
                                 'for now it is suppressing the beeps
     If txtBoxPos > 0 Then
        move cursor left within the box   '???

     Else if txtBoxPos = 0 Then
        nextBoxLeft.focus()
     End If
  End If

End Sub

无论如何,我正在研究这个问题,并会努力找到自己的答案。只是希望有人可以在这样的事情发生的情况下解决问题,如果我甚至在正确的轨道上?

要温柔,我自我教学,并且已经在这里呆了几个星期。

2 个答案:

答案 0 :(得分:2)

我不确定我是否理解控件在窗体上的布局,但TextBox确实有一个属性可以告诉您插入符号的位置,并且它被称为SelectionStart。< / p>

尽管有名称,但当没有文本实际被选中时,它也有效。

哦,你不需要编写一个方法来确定字符串的长度:只需使用Length属性。由于您是新用户,请记住字符串可以是null(或用VB术语中的Nothing),因此您需要在使用Length之前检查是否属于这种情况。一般来说,Text属性不会是null,但您要牢记这一点。

答案 1 :(得分:0)

感谢上午,我找到了解决办法。

   Private Sub TextBox3_KeyDown(sender As System.Object, e As System.Windows.Forms.KeyEventArgs) Handles TextBox3.KeyDown
    Dim length As Integer
    length = TextBox3.TextLength
    Dim position As Integer
    position = TextBox3.SelectionStart
    If e.KeyData = Keys.Left Then
        e.SuppressKeyPress = True

        If position = 0 Then
            TextBox2.Focus()
        ElseIf position > 0 Then
            TextBox3.SelectionStart = (position - 1)
        End If
    End If
    If e.KeyData = Keys.Right Then
        e.SuppressKeyPress = True
        If position = length Then
            TextBox1.Focus()
        ElseIf position < length Then
            TextBox3.SelectionStart = (position + 1)
        End If
    End If


End Sub