簡體   English   中英

在RichTextBox_Click事件中獲取插入符位置

[英]Get caret position in RichTextBox_Click event

我正在使用包含RichTextBox的文本編輯器。 我要實現的功能之一是隨時在TextBox顯示上述RichTextBox插入符號的當前Line和Column。

這是我使用的部分代碼(其余代碼與我的問題無關):

int selectionStart = richTextBox.SelectionStart;
int lineFromCharIndex = richTextBox.GetLineFromCharIndex(selectionStart);
int charIndexFromLine = richTextBox.GetFirstCharIndexFromLine(lineFromCharIndex);

currentLine = richTextBox.GetLineFromCharIndex(selectionStart) + 1;
currentCol = richTextBox.SelectionStart - charIndexFromLine + 1;

在這一點上,我應該提到,當有人使用RichTextBox ,插入符號可以通過三種方式更改位置:

  • 通過更改RichTextBoxText
  • 通過使用鍵盤上的箭頭鍵
  • 通過單擊RichTextBox上的任意位置

我上面發布的代碼在前兩種情況下沒有問題。 但是,在第三種情況下它實際上並不起作用。

我嘗試使用Click事件,但我注意到selectionStart變量將始終獲得0值,這意味着我總是獲得相同且錯誤的結果。 此外,在其他事件(例如MouseClickMouseUp上使用相同的代碼也無法解決我的問題,因為即使在這些事件的持續時間內selectionStart為0。

因此,每當用戶單擊RichTextBox ,如何獲取當前的Line和column?

您想要類似的東西:

private void richTextBox1_MouseUp(object sender, MouseEventArgs e)
{
        RichTextBox box = (RichTextBox)sender;
        Point mouseLocation = new Point(e.X, e.Y);
        box.SelectionStart = box.GetCharIndexFromPosition(mouseLocation);
        box.SelectionLength = 0;
        int selectionStart = richTextBox.SelectionStart;
        int lineFromCharIndex = box.GetLineFromCharIndex(selectionStart);
        int charIndexFromLine = box.GetFirstCharIndexFromLine(lineFromCharIndex);

        currentLine = box.GetLineFromCharIndex(selectionStart) + 1;
        currentCol = box.SelectionStart - charIndexFromLine + 1;
}

在我看來,您真正想要的是處理TextBoxBase.SelectionChanged事件。 然后,導致選擇更改的任何操作都將調用您的代碼,並且作為附加的好處,當前選擇將在調用事件處理程序時進行更新,並且可以確保獲取正確的值。

如果那不能解決您的特定需求,那么我一定不能理解這個問題。 在這種情況下,請提供一個良好的, 最少的完整的代碼示例 ,以清楚地顯示您要執行的操作,並准確描述該代碼的功能以及與您想要的代碼有何不同。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM