Archive for March, 2009

Aggiungere colore di sfondo alla DateTimePicker

March 31st, 2009

Di Default la classe DateTimePicker non ha il metodo BackColor. Qualora dovessere diventare indispensabile nei vostri progetti ecco la classe che lo implementa:

Imports System
Imports System.ComponentModel
Imports System.Drawing
Imports System.Windows.Forms
 
Public Class ExtendedDateTimePicker
    Inherits DateTimePicker
 
    Private m_BackBrush As SolidBrush
 
    < _
        Browsable(True), _
        DesignerSerializationVisibility( _
            DesignerSerializationVisibility.Visible _
        ) _
    > _
    Public Overrides Property BackColor() As Color
        Get
            Return MyBase.BackColor
        End Get
        Set(ByVal Value As Color)
            If Not m_BackBrush Is Nothing Then
                m_BackBrush.Dispose()
            End If
            MyBase.BackColor = Value
            m_BackBrush = New SolidBrush(Me.BackColor)
            Me.Invalidate()
        End Set
    End Property
 
    Protected Overrides Sub WndProc(ByRef m As Message)
        Const WM_ERASEBKGND As Int32 = &H14
        If m.Msg = WM_ERASEBKGND Then
            Dim g As Graphics = Graphics.FromHdc(m.WParam)
            If m_BackBrush Is Nothing Then
                m_BackBrush = New SolidBrush(Me.BackColor)
            End If
            g.FillRectangle(m_BackBrush, Me.ClientRectangle)
            g.Dispose()
        Else
            MyBase.WndProc(m)
        End If
    End Sub
 
    Protected Overloads Overrides Sub Dispose( _
        ByVal disposing As Boolean _
    )
        If disposing AndAlso Not m_BackBrush Is Nothing Then
            m_BackBrush.Dispose()
        End If
        MyBase.Dispose(disposing)
    End Sub
End Class

Un solo piccolissimo problema: non funziona con lo style di Windows Vista.