2013-02-28 82 views
4

我有一個Windows窗體文本框,後臺線程每秒更新一次值。 如果我將光標置於文本框內,它將在下次更新時鬆開當前位置。與文本選擇相同的東西。如何在沒有SelectionStart的情況下設置TextBox光標位置

我試圖解決它像

protected void SetTextProgrammatically(string value) 
    { 
     // save current cursor position and selection 
     int start = textBox.SelectionStart; 
     int length = textBox.SelectionLength; 

     // update text 
     textBox.Text = value; 

     // restore cursor position and selection 
     textBox.SelectionStart = start; 
     textBox.SelectionLength = length; 
    } 

它的工作原理很好的大部分時間。下面是情況時,它不工作:
1)我把光標放在文本的結尾在文本框中
2)按SHIFT鍵移動光標到使用<左 - 箭頭鍵
選擇將無法正常工作。

它看起來像組合SelectionStart=10SelectionLength=1自動將光標移動到位置11(不是我想要的那樣)。

請讓我知道,如果有什麼我可以做的!我正在使用Framework.NET 2.0。
必須有方法來設置光標在除SelectionStart+SelectionLength之外的文本框中的位置。

+0

什麼令人興奮的*它會在下次更新時丟失當前位置*是否意味着?你想達到什麼目的? – sloth 2013-02-28 14:39:05

+0

這意味着光標將跳轉到文本的開頭 – walruz 2013-02-28 14:44:57

+0

我希望此文本框僅用於任何其他文本框。它現在的工作方式有時令人惱火。我的意思是我可以選擇文本框內的文本只從左到右移動。而我不能從右向左移動 – walruz 2013-02-28 14:54:15

回答

3

我找到了解決方案!

 // save current cursor position and selection 
     int start = textBox.SelectionStart; 
     int length = textBox.SelectionLength; 

     Point point = new Point(); 
     User32.GetCaretPos(out point); 

     // update text 
     textBox.Text = value; 

     // restore cursor position and selection 
     textBox.Select(start, length); 
     User32.SetCaretPos(point.X, point.Y); 

現在它的工作就像它應該。

4
//save position 
      bool focused = textBox1.Focused; 
      int start = textBox1.SelectionStart; 
      int len = textBox1.SelectionLength; 
      //do your work 
      textBox1.Text = "duviubobioub"; 
      //restore 
      textBox1.SelectionStart = start; 
      textBox1.SelectionLength = len ; 
      textBox1.Select(); 
+1

我看不出您的建議和我已經使用的代碼之間的區別。 – walruz 2013-02-28 14:50:35

+0

對不起。我忘了Select() – 2013-02-28 14:55:00

+0

不幸的是,這不是解決方案 - 沒有任何改變。我仍然無法選擇文本框內的文本從右向左移動光標。 – walruz 2013-02-28 15:12:38

0

要在沒有選擇的文本框中設置光標位置開始...!

textbox1.Select(textbox1.text.length,0); /* ===> End of the textbox */ 
    textbox1.Select(0,0);     /* ===> Start of the textbox */ 
相關問題