Smith
Smith

Reputation: 5961

Get text from textbox in cursor position .net

I need to get text from a textbox in winforms, i need to get the text that the cursor is in between e.g

Hello or posit|ion or look

This should return the word position (Note here i used the pipe as the cursor)

Do you know any technique i can use for this

Upvotes: 3

Views: 1441

Answers (3)

UnhandledExcepSean
UnhandledExcepSean

Reputation: 12804

I tested this real quick and it seems like it works consistently

Private Function GetCurrentWord(ByRef txtbox As TextBox) As String
    Dim CurrentPos As Integer = txtbox.SelectionStart
    Dim StartPos As Integer = CurrentPos
    Dim EndPos As Integer = txtbox.Text.ToString.IndexOf(" ", StartPos)

    If EndPos < 0 Then
        EndPos = txtbox.Text.Length
    End If

    If StartPos = txtbox.Text.Length Then
        Return ""
    End If

    StartPos = txtbox.Text.LastIndexOf(" ", CurrentPos)
    If StartPos < 0 Then
        StartPos = 0
    End If

    Return txtbox.Text.Substring(StartPos, EndPos - StartPos).Trim
End Function

Upvotes: 4

Smith
Smith

Reputation: 5961

Thanks for all who tried to help,

i got a better, simpler approach without looping

Dim intCursor As Integer = txtInput.SelectionStart
Dim intStart As Int32 = CInt(IIf(intCursor - 1 < 0, 0, intCursor - 1))
Dim intStop As Int32 = intCursor
intStop = txtInput.Text.IndexOf(" ", intCursor)
intStart = txtInput.Text.LastIndexOf(" ", intCursor)
If intStop < 0 Then
 intStop = txtInput.Text.Length
End If
If intStart < 0 Then
  intStart = 0
End If
debug.print( txtInput.Text.Substring(intStart, intStop - intStart).Trim)

thanks all

Upvotes: 4

Dumbo
Dumbo

Reputation: 14112

Try something like this:

private void textBox1_MouseHover(object sender, EventArgs e)
{
    Point toScreen = textBox1.PointToClient(new Point(Control.MousePosition.X + textBox1.Location.X, Control.MousePosition.Y + textBox1.Location.Y));

    textBox1.SelectionStart = toScreen.X - textBox1.Location.X;
    textBox1.SelectionLength = 5; //some random number

    MessageBox.Show(textBox1.SelectedText + Environment.NewLine +  textBox1.SelectionStart.ToString());
}

It works somehow for me but also depends if your textbox is a added control to the form itself. if it is inside a panel or something the code should be changed.

Edit It seems that I misunderstood your question, I though you need to select text when mouse goes over it! Sorry! I beleive you can only do this task using a RichTextBox where you can get the position of the caret in it!

Upvotes: 2

Related Questions