次の方法で共有


方法: ComboBox コントロールに可変サイズのテキストを作成する

この例では、ComboBox コントロール内のテキストのカスタム描画を示します。 項目が特定の条件を満たすと、大きなフォントで描画され、赤に変わります。

Private Sub ComboBox1_MeasureItem(ByVal sender As Object, ByVal e As _
System.Windows.Forms.MeasureItemEventArgs) Handles ComboBox1.MeasureItem
    Dim bFont As New Font("Arial", 8, FontStyle.Bold)
    Dim lFont As New Font("Arial", 12, FontStyle.Bold)
    Dim siText As SizeF

    If ComboBox1.Items().Item(e.Index) = "Two" Then
        siText = e.Graphics.MeasureString(ComboBox1.Items().Item(e.Index), _
lFont)
    Else
        siText = e.Graphics.MeasureString(ComboBox1.Items().Item(e.Index), bFont)
    End If

    e.ItemHeight = siText.Height
    e.ItemWidth = siText.Width
End Sub

Private Sub ComboBox1_DrawItem(ByVal sender As Object, ByVal e As _
System.Windows.Forms.DrawItemEventArgs) Handles ComboBox1.DrawItem
    Dim g As Graphics = e.Graphics
    Dim bFont As New Font("Arial", 8, FontStyle.Bold)
    Dim lFont As New Font("Arial", 12, FontStyle.Bold)

    If ComboBox1.Items().Item(e.Index) = "Two" Then
        g.DrawString(ComboBox1.Items.Item(e.Index), lfont, Brushes.Red, _
e.Bounds.X, e.Bounds.Y)
    Else
        g.DrawString(ComboBox1.Items.Item(e.Index), bFont, Brushes.Black, e.Bounds.X, e.Bounds.Y)
    End If
End Sub

コードのコンパイル

この例では、次のものが必要です。

  • Windows フォーム。

  • ComboBox という名前のコントロール ListBox1 には、Items プロパティに 3 つの項目があります。 この例では、3 つの項目の名前は "One", Two", and Three"です。 ComboBox1DrawMode プロパティを OwnerDrawVariableに設定する必要があります。

    手記

    この手法は、ListBox コントロールにも適用できます。ComboBoxListBox に置き換えることができます。

  • System.Windows.Forms および System.Drawing 名前空間への参照。

関連項目