C# RichTextBox 做简单的HTML代码编辑器 ---------左侧显示行号
生活随笔
收集整理的這篇文章主要介紹了
C# RichTextBox 做简单的HTML代码编辑器 ---------左侧显示行号
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
說明:此顯示行號為實(shí)際行號,不論是空行還是自動換行,都計算在內(nèi),跟實(shí)際IDE的行號不同,同步滾動會有半行高度以內(nèi)的誤差。
實(shí)現(xiàn)原理,在RichTextBox?編輯器左側(cè)放置另一RichTextBox (或其它控件也可),行號為編輯器實(shí)際文字行數(shù),滾動時計算文字滾動高度,再根據(jù)行高算出當(dāng)前行大約位置,左側(cè)自動滾動到當(dāng)前行。
如果想準(zhǔn)確的話,可以不用行,直接拿到文字滾動高度,右側(cè)行號也滾動到相應(yīng)高度即可。
//行號 生成顯示 這里rtbLineNum用的 RichTextBox,也可以用其它private void ShowLineNum(){rtbLineNum.Text = "";//計算行高,行數(shù)int linesLength = 0;var pFirst = tbEditor.GetPositionFromCharIndex(0);var pEnd = tbEditor.GetPositionFromCharIndex(tbEditor.Text.Length);if (pEnd.Y > pFirst.Y){var pSecondLine = tbEditor.GetPositionFromCharIndex(tbEditor.GetFirstCharIndexFromLine(1));var lineHeight = pSecondLine.Y - pFirst.Y;linesLength = (pEnd.Y - pFirst.Y) / lineHeight;}else{linesLength = 1;}//生成行數(shù)for (var i = 0; i < linesLength; i++){rtbLineNum.AppendText(i + 1 + "\n");}//行號右對齊rtbLineNum.SelectAll();rtbLineNum.SelectionAlignment = HorizontalAlignment.Right;}//上次滾動位置 行private int _scrollToLine = 0;//同步滾動private void SyncSrollLocation(){//首行首字符初始位置var p = new Point(1,1); //計算行高int lineHeight = 0;var pFirst = tbEditor.GetPositionFromCharIndex(0);//首行位置var pEnd = tbEditor.GetPositionFromCharIndex(tbEditor.Text.Length);//最后一行位置if (pEnd.Y > pFirst.Y)//排除只有一行的情況{var pSecondLine = tbEditor.GetPositionFromCharIndex(tbEditor.GetFirstCharIndexFromLine(1));lineHeight = pSecondLine.Y - pFirst.Y;}//滾動高度 即首行位置移動高度 int scrollHeight = p.Y - pFirst.Y;//滾動到的行的位置 由于滾動大都并非整行滾動 所以四舍五入 ***程序的誤差就在這里var scrollTolineIndex = (int)Math.Round((double)(scrollHeight / lineHeight), MidpointRounding.AwayFromZero); if (_scrollToLine != scrollTolineIndex){_scrollToLine = scrollTolineIndex;var sStart = rtbLineNum.GetFirstCharIndexFromLine(scrollTolineIndex);//左側(cè)行號 當(dāng)前滾動到行 首字符位置if (sStart >= 0){rtbLineNum.SelectionStart = sStart;rtbLineNum.SelectionLength = 0;rtbLineNum.ScrollToCaret();}}}//編輯器 Resize事件private void tbEditor_Resize(object sender, EventArgs e){ShowLineNum();SyncSrollLocation();}//編輯器 TextChanged事件private void tbEditor_TextChanged(object sender, EventArgs e){ShowLineNum();SyncSrollLocation();}//編輯器 VScroll事件private void tbEditor_VScroll(object sender, EventArgs e){SyncSrollLocation();}?
總結(jié)
以上是生活随笔為你收集整理的C# RichTextBox 做简单的HTML代码编辑器 ---------左侧显示行号的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C# RichTextBox 实现循环查
- 下一篇: C# RichTextBox 做简单的H