[英]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
,插入符號可以通過三種方式更改位置:
RichTextBox
的Text
RichTextBox
上的任意位置 我上面發布的代碼在前兩種情況下沒有問題。 但是,在第三種情況下它實際上並不起作用。
我嘗試使用Click
事件,但我注意到selectionStart
變量將始終獲得0值,這意味着我總是獲得相同且錯誤的結果。 此外,在其他事件(例如MouseClick
和MouseUp
上使用相同的代碼也無法解決我的問題,因為即使在這些事件的持續時間內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.