C# 控件 RichTextBox 顯示行號,並且與Panel相互聯動


我們在使用到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         }
View Code

 

2:事件准備(啟用)如下事件

控件加載事件

1 private void txtFileView_TextChanged(object sender, EventArgs e)
2         {
3             showLineNo();
4         }
View Code

控件滾動事件(當算出的行數大於本控件長度)

1 private void txtFileView_VScroll(object sender, EventArgs e)
2         {
3             showLineNo();
4         }
View Code

完成后,直接啟用運行,Demo事例中的效果就出來,方便大家用於各種應用上.

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM