在.NET中获取光标位置文本框的文本

3
我需要在WinForms中从文本框中获取文本,我需要获取光标所在的文本,例如:

Hello or posit|ion or look

这应该返回单词 position (请注意,这里使用了竖线作为光标)

您知道我可以使用的任何技术吗?


使用 SelectedText 属性。 - Hans Passant
谢谢,我重新编辑了我的问题,实际上我已经得到了第二部分的答案。 - Smith
3个回答

3
我很快进行了测试,似乎它能够稳定工作。
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

@SpectralGhost,看看我的方法,虽然在看到你的代码之前我已经解决了这个问题。 - Smith

3

感谢所有尝试帮助我的人,

我找到了一种更好、更简单的方法,不需要循环。

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)

感谢大家


+1 我喜欢你使用 LastIndexOf 的方式,所以我更新了我的答案,不再使用循环。 - UnhandledExcepSean

2

尝试像这样:

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());
}

对我来说,它在某种程度上起作用,但也取决于您的文本框是否是添加到表单本身的控件。如果它在面板或其他东西中,代码应该更改。

编辑 看来我误解了你的问题,我以为你需要在鼠标悬停在文本上时选择文本!抱歉!我相信您只能使用 RichTextBox 执行此任务,在其中可以获取光标的位置!


你错了,请看一下我的方法和你解决方案上面的方法。 - Smith

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接