3

我需要从winforms中的文本框中获取文本,我需要获取光标之间的文本,例如

你好或位置|离子或看

这应该返回单词position(注意这里我使用管道作为光标)

你知道我可以用什么技术吗

4

3 回答 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
于 2011-12-11T23:05:58.700 回答
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)

谢谢大家

于 2011-12-12T08:33:24.243 回答
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可以获得插入符号位置的位置来完成此任务!

于 2011-12-11T22:51:03.637 回答