C# 控件 RichTextBox 显示行号,并且与Panel相互联动
程序员文章站
2022-05-18 12:03:50
我们在使用到WINFORM窗体工作中,要求RichTextBox 加入行号; 之前有看到大牛们写的,但是太复杂繁多,而且有用双TextBox进行联动,非常不错,今天我们尝试RichTextBox +Panel相互联动如下效果. 左侧灰色为Panel,右侧为RichTextBox 控件 1:准备Pan ......
我们在使用到winform窗体工作中,要求richtextbox 加入行号;
之前有看到大牛们写的,但是太复杂繁多,而且有用双textbox进行联动,非常不错,今天我们尝试richtextbox +panel相互联动如下效果.
左侧灰色为panel,右侧为richtextbox 控件
1:准备panel画布如下代码,当接到文件字符后进行坐标解析,绘制行号。
1 private void showlineno() 2 { 3 //获得当前坐标信息 4 point p = this.txtfileview.location; 5 int crntfirstindex = this.txtfileview.getcharindexfromposition(p); 6 7 int crntfirstline = this.txtfileview.getlinefromcharindex(crntfirstindex); 8 9 point crntfirstpos = this.txtfileview.getpositionfromcharindex(crntfirstindex); 10 11 p.y += this.txtfileview.height; 12 13 int crntlastindex = this.txtfileview.getcharindexfromposition(p); 14 15 int crntlastline = this.txtfileview.getlinefromcharindex(crntlastindex); 16 point crntlastpos = this.txtfileview.getpositionfromcharindex(crntlastindex); 17 18 //准备画图 19 graphics g = this.panel2.creategraphics(); 20 21 font font = new font(this.txtfileview.font, this.txtfileview.font.style); 22 23 solidbrush brush = new solidbrush(color.green); 24 25 //画图开始 26 27 //刷新画布 28 29 rectangle rect = this.panel2.clientrectangle; 30 brush.color = this.panel2.backcolor; 31 32 g.fillrectangle(brush, 0, 0, this.panel2.clientrectangle.width, this.panel2.clientrectangle.height); 33 34 brush.color = color.white;//重置画笔颜色 35 36 //绘制行号 37 38 int linespace = 0; 39 40 if (crntfirstline != crntlastline) 41 { 42 linespace = (crntlastpos.y - crntfirstpos.y) / (crntlastline - crntfirstline); 43 44 } 45 46 else 47 { 48 linespace = convert.toint32(this.txtfileview.font.size); 49 50 } 51 int brushx = this.panel2.clientrectangle.width - convert.toint32(font.size * 3); 52 53 int brushy = crntlastpos.y + convert.toint32(font.size * 0.21f); 54 for (int i = crntlastline; i >= crntfirstline; i--) 55 { 56 57 g.drawstring((i + 1).tostring(), font, brush, brushx, brushy); 58 59 brushy -= linespace; 60 } 61 62 g.dispose(); 63 64 font.dispose(); 65 66 brush.dispose(); 67 }
2:事件准备(启用)如下事件
控件加载事件
1 private void txtfileview_textchanged(object sender, eventargs e) 2 { 3 showlineno(); 4 }
控件滚动事件(当算出的行数大于本控件长度)
1 private void txtfileview_vscroll(object sender, eventargs e) 2 { 3 showlineno(); 4 }
完成后,直接启用运行,demo事例中的效果就出来,方便大家用于各种应用上.