c#写带行号的richTextBox 修正版
笔者最近在打造自己的博客自动发布程序,其中设计到编辑器的代码编写。一个基本的web编辑器包括所见即所得编辑器、源代码编辑器、以及预览部分。基本UI如下图:
在xhtml编辑器部分需要richtextbox带有显示行号和代码高亮的功能。于是google之,网上资源丰富,笔者在参考权衡之后决定使用c#写带行号的richTextBox 一文中的代码。不过在调试的时候却出了一点问题。
代码是正确的,但是却怎么也显示不了头6行的行号。笔者非常纳闷,发现richtextbox控件GetCharIndexFromPosition函数无法正确返回字符索引这个缺陷所致。于是,再仔细查看代码,将原代码中第一行
Point p = this.richTextBox1.Location;
修改为
Point p = new Point(0,0);
在此编译后就正确了。
下面给出完整代码:
private void ShowNumLines() { Point p = new Point(0, 0); 仅修改此行,其余请参考原文 int curIndex = this.rtbox_xhtml.GetCharIndexFromPosition(p); int curLine = this.rtbox_xhtml.GetLineFromCharIndex(curIndex); Point curPos = this.rtbox_xhtml.GetPositionFromCharIndex(curIndex); p.Y += this.rtbox_xhtml.Height; int curLastIndex = this.rtbox_xhtml.GetCharIndexFromPosition(p); int curLastLine = this.rtbox_xhtml.GetLineFromCharIndex(curLastIndex); Point curLastPos = this.rtbox_xhtml.GetPositionFromCharIndex(curLastIndex); Graphics g = this.xhtml_lines.CreateGraphics(); Font font = new Font(this.rtbox_xhtml.Font, this.rtbox_xhtml.Font.Style); SolidBrush brush = new SolidBrush(SystemColors.ControlDark); Rectangle rect = this.xhtml_lines.ClientRectangle; brush.Color = this.xhtml_lines.BackColor; g.FillRectangle(brush, 0, 0, this.xhtml_lines.ClientRectangle.Width, this.xhtml_lines.ClientRectangle.Height); brush.Color = SystemColors.ControlDark; // //绘制行号 int lineSpace = 0; if (curLine != curLastLine) { lineSpace = (curLastPos.Y - curPos.Y) / (curLastLine - curLine); } else { lineSpace = Convert.ToInt32(this.rtbox_xhtml.Font.Size); } int brushX = this.xhtml_lines.ClientRectangle.Width - Convert.ToInt32(font.Size * 3); int brushY = curLastPos.Y + Convert.ToInt32(font.Size * 0.18f);//惊人的算法啊!! for (int i = curLastLine; i >= curLine; i--) { g.DrawString((i + 1).ToString(), font, brush, brushX, brushY); brushY -= lineSpace; } g.Dispose(); font.Dispose(); brush.Dispose(); }
开源~开源~~~
还没有做好,做好后会考虑滴^_^
嗯,这个貌似很不错呢~希望能尽快做好吧~
C#我是不打算学了~已经学了很多语言了,自己年龄也上去了,不想折腾了,嘿~