2011-12-11 86 views
3

我需要從WinForms的一個文本框獲取文本,我需要獲取文本光標在如獲取從文本文本光標位置.NET

個招呼,或者斷定之間|離子或看

這將返回字position(注意,這裏我使用的管道作爲光標)

你知道的任何技術,我可以使用這個

+0

使用SelectedText屬性。 –

+0

謝謝,我重新編輯了我的問題,其實我得到了第二部分 – Smith

回答

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 
+0

+1好方法! –

+0

@SpectralGhost看看我的方法,雖然我看到你的代碼之前解決了這個問題 – Smith

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來完成這項任務,你可以在其中獲得插入符的位置!

+0

你錯了,看看我的方法在下面和你的解決方案之上 – Smith

+0

是的,很高興你做到了! –

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) 

謝謝全部

+0

+1我喜歡你使用LastIndexOf,所以我更新了我的答案,而不是循環。 – UnhandledExcepSean