VB.NET Tips - ComboBoxの簡単な拡張クラス
VB.NETの ComboBox には枠線(ボーダー)を表示するプロパティが標準ではありません。
ComboBox の FlatStyle を Flat に設定すると、 枠線が白色になりよく見えなくなります。
そこで、 ComboBox の簡単な拡張クラスをとして枠線の色を追加のプロパティとして作成しました。
クラス名は名前は ComboBoxEx とします。
ウインドウメッセージの処理の中で、 WM_PAINT のメッセージの処理でコンボボックスコントロールの枠を描画します。
枠線を指定する為のプロパティを BorderColor として定義しています。
ComboBoxの簡単な拡張クラス
01 | Imports System |
02 | Imports System.ComponentModel |
03 | Imports System.Drawing |
04 | Imports System.Drawing.Drawing2D |
05 | Imports System.Windows.Forms |
06 |
07 | ''' <summary> |
08 | ''' 拡張コンボボックスコントロール |
09 | ''' </summary> |
10 | ''' <remarks></remarks> |
11 | Public Class ComboBoxEx |
12 | Inherits System.Windows.Forms.ComboBox |
13 |
14 | Private Const WM_PAINT As Integer = &HF |
15 |
16 | ''' <summary> |
17 | ''' コンストラクタ |
18 | ''' </summary> |
19 | Sub New () |
20 | 'ComboBoxのコンストラクタを呼ぶ |
21 | MyBase . New () |
22 | End Sub |
23 |
24 | ''' <summary> |
25 | ''' Windowsメッセージ処理 |
26 | ''' </summary> |
27 | ''' <param name="m"> |
28 | Protected Overrides Sub WndProc( ByRef m As System.Windows.Forms.Message) |
29 | Select Case m.Msg |
30 | Case WM_PAINT |
31 | 'ペイントイベントでデフォルトの処理をさせる |
32 | MyBase .WndProc(m) |
33 | 'その後で強制的に枠描画 |
34 | Call DrawRectangle() |
35 |
36 | Case Else |
37 | MyBase .WndProc(m) |
38 | End Select |
39 | End Sub |
40 |
41 | ''' <summary> |
42 | ''' 枠描画関数 |
43 | ''' </summary> |
44 | ''' <remarks>再定義可能関数</remarks> |
45 | Protected Overridable Sub DrawRectangle() |
46 | 'グラフィッククラスの参照取得 |
47 | Dim g As Graphics = Me .CreateGraphics() |
48 | '枠の四角い領域 |
49 | Dim rect As Rectangle = Me .ClientRectangle |
50 | '描画用のペン生成 |
51 | Dim framePen As New Pen( Me .BorderColor) |
52 | Try |
53 | '枠描画 |
54 | g.DrawRectangle(framePen, rect.X, rect.Y, rect.Width - 1, rect.Height - 1) |
55 | Catch ex As Exception |
56 | Finally |
57 | 'ペンの解放 |
58 | framePen.Dispose() |
59 | End Try |
60 | End Sub |
61 |
62 | 'ボーダー色退避 |
63 | Private _BorderColor As Color = System.Drawing.SystemColors.ControlText |
64 |
65 | ''' <summary> |
66 | ''' ボーダー色プロパティ |
67 | ''' </summary> |
68 | ''' <value>Color値</value> |
69 | ''' <returns>Color値</returns> |
70 | Public Property BorderColor() As Color |
71 | Get |
72 | Return Me ._BorderColor |
73 | End Get |
74 | Set ( ByVal value As Color) |
75 | Me ._BorderColor = value |
76 | End Set |
77 | End Property |
78 |
79 | End Class |
このクラスを clsComboBoxEx.vb の様な名前で保存し、一度コンパイルすると、ツールボックスの中に ComboBoxExが現れるので、それをフォームに貼り付けます。 フォームに張り付けた時のプロパティウインドウに BorderColor があることがわかります。

