当前位置:编程学习 > C#/ASP.NET >>

c#写带行号的richTextBox

加两个控件:Panel/RichTextBox

 

view sourceprint?01 //方法 

02   

03 private void showLineNo() 

04   

05 { 

06   

07 //获得当前坐标信息 

08   

09 Point p = this.richTextBox1.Location; 

10 int crntFirstIndex = this.richTextBox1.GetCharIndexFromPosition(p); 

11   

12 int crntFirstLine = this.richTextBox1.GetLineFromCharIndex(crntFirstIndex); 

13   

14 Point crntFirstPos = this.richTextBox1.GetPositionFromCharIndex(crntFirstIndex); 

15   

16 // 

17 p.Y += this.richTextBox1.Height; 

18   

19 // 

20   

21      int crntLastIndex = this.richTextBox1.GetCharIndexFromPosition(p); 

22   

23      int crntLastLine = this.richTextBox1.GetLineFromCharIndex(crntLastIndex); 

24      Point crntLastPos = this.richTextBox1.GetPositionFromCharIndex(crntLastIndex); 

25   

26      // 

27   

28      // 

29   

30      //准备画图 

31      Graphics g = this.panel1.CreateGraphics(); 

32   

33      Font font = new Font(this.richTextBox1.Font,this.richTextBox1.Font.Style); 

34   

35      SolidBrush brush = new SolidBrush(Color.Green); 

36   

37      // 

38      // 

39   

40      //画图开始 

41   

42      //刷新画布 

43   

44      Rectangle rect = this.panel1.ClientRectangle; 

45      brush.Color = this.panel1.BackColor; 

46   

47 g.FillRectangle(brush, 0, 0, this.panel1.ClientRectangle.Width,this.panel1.ClientRectangle.Height); 

48   

49      brush.Color = Color.Green;//重置画笔颜色 

50   

51      // 

52      //绘制行号 

53   

54      int lineSpace = 0; 

55   

56      if (crntFirstLine != crntLastLine) 

57   

58      { 

59           lineSpace = (crntLastPos.Y - crntFirstPos.Y) / (crntLastLine - crntFirstLine); 

60   

61      } 

62   

63      else

64   

65      { 

66           lineSpace = Convert.ToInt32(this.richTextBox1.Font.Size); 

67   

68      } 

69   

70      int brushX = this.panel1.ClientRectangle.Width - Convert.ToInt32(font.Size * 3); 

71   

72      int brushY = crntLastPos.Y+ Convert.ToInt32(font.Size*0.21f);//惊人的算法啊!! 

73      for (int i = crntLastLine; i >= crntFirstLine;i-- ) 

74   

75      { 

76   

77            g.DrawString((i + 1).ToString(), font, brush, brushX, brushY); 

78   

79            brushY -= lineSpace; 

80      } 

81   

82      g.Dispose(); 

83   

84      font.Dispose(); 

85   

86      brush.Dispose(); 

87 }


补充:软件开发 , C# ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,