获取从文本文本光标位置.NET
我需要从WinForms的一个文本框获取文本,我需要获取文本光标在如获取从文本文本光标位置.NET
个招呼,或者断定之间|离子或看
这将返回字position
(注意,这里我使用的管道作为光标)
你知道的任何技术,我可以使用这个
我测试了这个真正的快,它看起来像它的工作原理一致
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
+1好方法! –
@SpectralGhost看看我的方法,虽然我看到你的代码之前解决了这个问题 – Smith
尝试是这样的:
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
是的,很高兴你做到了! –
感谢所有谁试图帮助,
我有一个更好的,更简单的方法不用循环
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
使用SelectedText属性。 –
谢谢,我重新编辑了我的问题,其实我得到了第二部分 – Smith