<このサンプルの概要>
VB.NETのComboBoxってなぜReadOnlyプロパティが無いのだろう。TextBox にはReadOnlyプ
ロパティがあり、Enabled=False とは違って文字をハッキリ表示出来ます。しかしComboB
oxにはReadOnlyプロパティが無いのでEnabledをFalseにするしかありません。
でもEnabled=Falseでは文字が薄くなってしまいます。そこで、ComboBoxに ReadOnlyプロ
パティを付けたサンプルを作ってみました。
Public Class ComboBoxPlus
Inherits System.Windows.Forms.ComboBox
Private _BackColorOrg As System.Drawing.Color
Private _ReadOnly As Boolean
Public Property [ReadOnly]() As Boolean
Get
Return _ReadOnly
End Get
Set(ByVal Value As Boolean)
_ReadOnly = Value
If Value Then
BackColor = System.Drawing.SystemColors.Control
SetStyle(ControlStyles.UserMouse, True)
Else
BackColor = _BackColorOrg
SetStyle(ControlStyles.UserMouse, False)
End If
End Set
End Property
Public Sub New()
MyBase.New()
_BackColorOrg = BackColor
End Sub
Protected Overrides Sub OnKeyDown(ByVal e As System.Windows.Forms.KeyEventArgs)
If _ReadOnly Then
e.Handled = True
End If
End Sub
Protected Overrides Sub OnKeyUp(ByVal e As System.Windows.Forms.KeyEventArgs)
If _ReadOnly Then
e.Handled = True
End If
End Sub
Protected Overrides Sub OnKeyPress(ByVal e As System.Windows.Forms.KeyPressEventArgs)
If _ReadOnly Then
e.Handled = True
End If
End Sub
End Class
Public Class Form1
Inherits System.Windows.Forms.Form
Public Sub New()
MyBase.New()
InitializeComponent()
End Sub
Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
If disposing Then
If Not (components Is Nothing) Then
components.Dispose()
End If
End If
MyBase.Dispose(disposing)
End Sub
Private components As System.ComponentModel.IContainer
Friend WithEvents ComboBox1 As ComboBoxPlus
Friend WithEvents ComboBox2 As ComboBoxPlus
Private Sub InitializeComponent()
Me.ComboBox1 = New ComboBoxPlus
Me.ComboBox2 = New ComboBoxPlus
Me.SuspendLayout()
'ComboBox1
Me.ComboBox1.Location = New System.Drawing.Point(40, 16)
Me.ComboBox1.Name = "ComboBox1"
Me.ComboBox1.Size = New System.Drawing.Size(216, 20)
Me.ComboBox1.TabIndex = 0
Me.ComboBox1.Text = "ComboBox1"
'ComboBox2
Me.ComboBox2.Location = New System.Drawing.Point(40, 56)
Me.ComboBox2.Name = "ComboBox2"
Me.ComboBox2.Size = New System.Drawing.Size(216, 20)
Me.ComboBox2.TabIndex = 1
Me.ComboBox2.Text = "ComboBox2"
'Form1
Me.AutoScaleBaseSize = New System.Drawing.Size(5, 12)
Me.ClientSize = New System.Drawing.Size(292, 102)
Me.Controls.Add(Me.ComboBox2)
Me.Controls.Add(Me.ComboBox1)
Me.Name = "Form1"
Me.Text = "Form1"
Me.ResumeLayout(False)
End Sub
Private Sub Form1_Load( _
ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
ComboBox1.Items.Add("データ1")
ComboBox1.Items.Add("データ2")
ComboBox1.Items.Add("データ3")
ComboBox1.Items.Add("データ4")
ComboBox1.Items.Add("データ5")
ComboBox1.SelectedIndex = 2
ComboBox2.Items.Add("データ1")
ComboBox2.Items.Add("データ2")
ComboBox2.Items.Add("データ3")
ComboBox2.Items.Add("データ4")
ComboBox2.Items.Add("データ5")
ComboBox2.SelectedIndex = 2
ComboBox2.ReadOnly = True
End Sub
End Class
|