2020年5月17日 星期日

vb.net listbox 內容置中 [listbox content center]


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        ListBox1.DrawMode = DrawMode.OwnerDrawFixed

        For x As Integer = 0 To 7

            ListBox1.Items.Add(x)

        Next

    End Sub


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
    Private Sub ListBox1_DrawItem(ByVal sender As Object, ByVal e As System.Windows.Forms.DrawItemEventArgs) Handles ListBox1.DrawItem

        Dim g As Graphics = e.Graphics


        Dim br As SolidBrush

        Dim s As String

        Dim sf As New StringFormat


        sf.Alignment = StringAlignment.Center


        Try

            s = ListBox1.Items.Item(e.Index).ToString

        Catch ex As Exception

            s = ""

            Trace.WriteLine(ex.ToString)

        End Try


        br = New SolidBrush(Color.FromArgb(255, 251, 156))


        g.FillRectangle(br, e.Bounds)


        If CBool(e.State And DrawItemState.Selected) Then

            g.FillRectangle(Brushes.LightBlue, e.Bounds)

        End If


        g.DrawString(s, ListBox1.Font, Brushes.Black, _

        RectangleF.op_Implicit(e.Bounds), sf)


        br.Dispose()

    End Sub

沒有留言:

張貼留言