Ad

Click And Recognise Part Of Text In Textbox Vb.net

- 1 answer

I am trying to make a program that utilises a textbox that has text options listed in it that can be clicked on.

As a textbox example:

[Selection:<1><2><3>]

so the user could then as example click on (over the text) <2> to select the 2nd option or <3> so select the 3rd option. The idea comes from the AutoCAD commands prompt which uses a simular system.

How would I achive somthing like this in vb.net code (if its even possible)?

Ad

Answer

Try this:

Private Sub TextBox1_Click(sender As Object, e As EventArgs) Handles TextBox1.Click
    Dim SplitText As String() = TextBox1.Text.Split(CChar("<"), ">")
    Dim SelectedText As String = GetSelectedText()
    Dim Options As New List(Of String)

    If Not SelectedText = "" Then
        For i = 0 To SplitText.Length - 1
            If IsNumeric(SplitText(i)) Then
                Options.Add("<" & SplitText(i) & ">")
            End If
        Next
        For i = 0 To Options.Count - 1
            If SelectedText = Options(i) Then
                'Put your code here if it is the current option in the loop equals the selected option.
                'I added a messagebox just so you can see the current option.
                MessageBox.Show("You selected option: " & Options(i))
            End If
        Next
    End If
End Sub

Private Function GetSelectedText()
    Dim CursorPosition As Integer = TextBox1.SelectionStart
    Dim SelectedNumber As String = ""
    Dim NumberLength As Integer = 0

    If CursorPosition = 0 Or CursorPosition = TextBox1.Text.Length Then
        Return ""
    End If
    Do Until Mid(TextBox1.Text, CursorPosition - NumberLength, 1) = "<"
        NumberLength += 1
    Loop
    SelectedNumber = Mid(TextBox1.Text, CursorPosition - NumberLength, NumberLength + 1)
    NumberLength = 0
    CursorPosition += 1
    Do Until Mid(TextBox1.Text, CursorPosition + NumberLength, 1) = ">"
        NumberLength += 1
    Loop
    SelectedNumber &= Mid(TextBox1.Text, CursorPosition, NumberLength + 1)

    If IsNumeric(SelectedNumber.Remove(0, 1).Remove(SelectedNumber.Length - 2, 1)) Then
        Return SelectedNumber
    Else
        Return ""
    End If
End Function

I put this inside of the textbox click event, and it works. I did not try putting the code in any other events. I assume that the textbox is named: TextBox1.

Ad
source: stackoverflow.com
Ad