111,126
社区成员
发帖
与我相关
我的任务
分享
//本来想重绘一个 ListBox,用来显示两行文字,可是继承 ListBox重写了OnPaint事件后,
//滚动条好像不起做用了,无论拉到哪里,都是从第一个向后显示。也就是说OnPaint好像有问题。
//代码如下:
1 using System;
2 using System.Collections.Generic;
3 using System.Text;
4 using System.Windows.Forms;
5 using System.Drawing;
6 using System.Collections;
7
8
9 namespace HappyFarmDotNet
10 {
11 class ListBoxEx : System.Windows.Forms.ListBox
12 {
13 public ListBoxEx()
14 {
15 ItemHeight = 65;
16
17 this.SetStyle(ControlStyles.UserPaint, true);
18
19 Click += new EventHandler(OnClick);
20 }
21 protected override void OnPaint(PaintEventArgs e)
22 {
23
24 for (int i = 0; i < Items.Count; i++)
25 {
26 if (SelectedIndex == i)
27 {
28 DrawSelectedItems(e, i);
29 }
30 else
31 {
32 DrawNomalItems(e,i);
33 }
34 }
35 base.OnPaint(e);
36 }
37
38 private void OnClick(object sender, EventArgs e)
39 {
40 this.Refresh();
41 }
42 private void DrawNomalItems(PaintEventArgs e, int x)
43 {
44 // e.Graphics.TranslateTransform(this.AutoScrollOffset.X, this.AutoScrollOffset.Y);
45 e.Graphics.DrawRectangle(Pens.Beige, 1, (x * 65 + 1),
e.ClipRectangle.Width - 3, 45);
46 e.Graphics.DrawString(Items[x].ToString(),
Font, Brushes.SkyBlue, 65, (x * 65) + 8);
47 }
48
49 private void DrawSelectedItems(PaintEventArgs e, int x)
50 {
51 //画边框
52 e.Graphics.DrawRectangle(Pens.Beige, 1, (x * 65 + 1),
e.ClipRectangle.Width - 3, 45);
53 //填充选中Item背景
54 e.Graphics.FillRectangle(Brushes.RoyalBlue, 1 + 1, (x * 65 + 1 + 1),
e.ClipRectangle.Width - 3 - 1, 45 - 1);
55 //定义虚线画笔并绘边框
56 Pen Line = new Pen(Color.Black, 1);
57 Line.DashStyle = System.Drawing.Drawing2D.DashStyle.Dot;
58
59 e.Graphics.DrawRectangle(Line, 1, (x * 65 + 1),
e.ClipRectangle.Width - 3, 45);
60 //画文字
61 e.Graphics.DrawString(Items[x].ToString(), Font, Brushes.SkyBlue,
65, (x * 65) + 8);
62
63 }
64 }
65 }
66
//请高手指点。谢谢
