2010-07-20 11 views

回答

1

TextBox.SelectionStart財產上的文本框可以幫助你。從鏈接:

如果沒有選擇,SelectionStart值獲取或設置光標的位置。

+0

我嘗試過使用SelectionStart,但選擇點不會右鍵單擊。 謝謝。 – 2010-07-22 15:21:07

0

如何:

// Get the click coordinates relative to the TextBox. 
    int clickX = (int)e.GetPosition(textBox).X; 
    int clickY = (int)e.GetPosition(textBox).Y; 
    int startPosition = 0; 
    double currentHeight = 0; 
    double calculatedHeight = 0; 
    int charIndex; 

    TextBlock tb = new TextBlock(); 
    tb.Width = this.textBox.Width; 
    tb.FontFamily = this.textBox.FontFamily; 
    tb.FontSize = this.textBox.FontSize; 
    for (charIndex = 0; charIndex < this.textBox.Text.Length; charIndex++) 
    { 
     tb.Text = this.textBox.Text.Substring(startPosition, charIndex - startPosition + 1); 
     if (tb.ActualHeight > currentHeight) 
     { 
      if (currentHeight == 0) 
      { 
       currentHeight = tb.ActualHeight; 
       calculatedHeight = currentHeight; 
      } 
      else 
      { 
       startPosition = charIndex + 1; 
       charIndex++; 
       tb.Text = this.textBox.Text.Substring(startPosition, charIndex - startPosition + 1); 
       currentHeight = tb.ActualHeight; 
       calculatedHeight += currentHeight; 
      } 
     } 

     if (tb.ActualWidth > clickX && calculatedHeight > clickY) break; 
    } 

    _insertPoint = charIndex; 

我不會說謊,並說這是優雅的,但它似乎很好地工作。

+0

謝謝安迪。我在Google的研究中遇到過這種方法,但我忽略了提及這是一個多行TextBox。這種方法可能適用於兩個維度,但數學看起來很複雜。 – 2010-07-22 15:26:16

+0

啊,好的。我更新了代碼以反映這一點。 – 2010-07-23 02:27:44

+0

它很接近(如果我添加「tb.TextWrapping = TextWrapping.Wrap」這一行),但它不夠準確,無法找到正確的插入點。 謝謝你的嘗試。這是一個原型,所以我現在不需要解決它。當我們真正實現它時,我可能會回到這個問題上。 – 2010-07-28 23:30:19

相關問題