views:

151

answers:

1

Basically I have a series of lines in a textbox like this:

### = 1232, 1234, 1236, 1238, 123A, 123C ; comment here I want to show a button when the caret (cursor pipe thing) in the textbox goes is in a number so like:

... , 12|31, .... or ... , 123|1, .... etc (the pipe being the caret)

I have written code to check if it is in a number and to get the number when the button is clicked, but it doesn't work correctly if I put the code in the selection changed event.

oh and the numbers can be upto 8 digits long and hex.

+1  A: 

TextBox doesn't have an event that tells you that the user moved the caret. You'll have to synthesize one, possible with the Application.OnIdle event. It runs after all input events (mouse, keyboard) are processed. You'll do a bit of extra unnecessary work but you'll never notice since this code runs in "human-time". For example:

Public Class Form1

  Public Sub New()
    InitializeComponent()
    AddHandler Application.Idle, AddressOf UpdateButtonState
  End Sub

  Private Sub updateButtonState(ByVal sender As Object, ByVal e As EventArgs)
    Const hexdigits As String = "0123456789ABCDEF"
    Dim caretPos As Integer = TextBox1.SelectionStart
    Dim enable As Boolean = caretPos > 0 AndAlso caretPos < TextBox1.Text.Length
    If enable Then
      Dim left As Char = Char.ToUpper(TextBox1.Text(caretPos - 1))
      Dim right As Char = Char.ToUpper(TextBox1.Text(caretPos))
      If Not hexdigits.Contains(left) OrElse Not hexdigits.Contains(right) Then enable = False
    End If
    Button1.Enabled = enable
  End Sub
End Class

If the extra work bothers you then check if the text box has the focus and keep track of its last SelectionStart value.

Hans Passant