新手,還在學校奮斗中,頭一回分享代碼, 在網上看到一些例子有了靈感,用按鈕加ListBox的OwnerDrawFixed繪制做了一個可以實現收縮的菜單控件,不足之處望大佬們指點
1 using System;
2 using System.Collections.Generic;
3 using System.ComponentModel;
4 using System.Data;
5 using System.Drawing;
6 using System.Linq;
7 using System.Text;
8 using System.Threading.Tasks;
9 using System.Windows.Forms;
10
11 namespace WindowsFormsApplication1
12 {
13 public partial class Form1 : Form
14 {
15 private Color SetColor = Color.AliceBlue;
16
17 int a, b, c = 0;
18 public Form1()
19 {
20 InitializeComponent();
21 }
22
23 private void Form1_Load(object sender, EventArgs e)
24 {
25 LoadList();
26 }
27
28 private void LoadList()
29 {
30 button1.BringToFront();
31 button1.Dock = DockStyle.Top;
32 listBox1.BringToFront();
33 listBox1.Dock = DockStyle.Top;
34 button2.BringToFront();
35 button2.Dock = DockStyle.Top;
36 listBox2.BringToFront();
37 listBox2.Dock = DockStyle.Top;
38 button3.BringToFront();
39 button3.Dock = DockStyle.Top;
40 listBox3.BringToFront();
41 listBox3.Dock = DockStyle.Top;
42 listBox1.Visible = false;
43 listBox2.Visible = false;
44 listBox3.Visible = false;
45 }
46
47
48 private void button1_Click(object sender, EventArgs e)
49 {
50 if (a == 0)
51 {
52 listBox1.Visible = true;
53 a = 1;
54 }
55 else
56 {
57 a = 0;
58 listBox1.Visible = false;
59 }
60 }
61
62
63
64 private void button2_Click(object sender, EventArgs e)
65 {
66 if (b == 0)
67 {
68 listBox2.Visible = true;
69 b = 1;
70 }
71 else
72 {
73 listBox2.Visible = false;
74 b = 0;
75 }
76 }
77
78 private void button3_Click(object sender, EventArgs e)
79 {
80 if (c == 0)
81 {
82 listBox3.Visible = true;
83 c = 1;
84 }
85 else
86 {
87 listBox3.Visible = false;
88 c = 0;
89 }
90 }
91
92 private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
93 {
94 ListBox lb = sender as ListBox;
95 e.DrawBackground();
96 Brush myBrush = Brushes.Black;
97 if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
98 {
99 myBrush = new SolidBrush(SetColor);
100 e.Graphics.FillRectangle(myBrush, e.Bounds);
101 }
//可針對每一列數據更改背景色
102 switch (e.Index)
103 {
104 case 0:
105 myBrush = Brushes.Red;
106 break;
107 case 1:
108 myBrush = Brushes.Orange;
109 break;
110 case 2:
111 myBrush = Brushes.Purple;
112 break;
113 case 3:
114 myBrush = Brushes.Aquamarine;
115 break;
116 case 4:
117 myBrush = Brushes.BlueViolet;
118 break;
119 }
120 StringFormat strFormat = new StringFormat();
121 strFormat.Alignment = StringAlignment.Center;
122 strFormat.LineAlignment = StringAlignment.Center;
123 e.DrawFocusRectangle();
124 e.Graphics.DrawString(lb.Items[e.Index].ToString(), e.Font, myBrush, e.Bounds, strFormat);
125 }
126
127
128 }
129 }
130 效果圖
類似效果用ListView做更簡單,但我個人感覺ListBox效果更好。
歡迎各位大佬指點交流。。。