How can I retrieve the dropdown state of a DateTimePicker?

.net, datetimepicker, vb.net, winforms

Solution

What you've done is fine for one-off instances, but if your form/class contains multiple controls, tracking them all with variables can become unwieldy and difficult to follow.

A simple alternative method is to use the control's `.Tag` property to record the variable state and test that. However, a better method is to create your own class that inherits the control and add the property you want, pretty much using the same code you already have. So, in your case, you would add a class called say "MyDateTimePicker" with this code:

Public Class MyDateTimePicker
    Inherits DateTimePicker

    Dim _isDroppedDown As Boolean = False

    Public Property IsDroppedDown() As Boolean
        Get
            IsDroppedDown = _isDroppedDown
        End Get
        Set(value As Boolean)
            _isDroppedDown = value
        End Set
    End Property

    Private Sub MyDateTimePicker_CloseUp(sender As Object, e As System.EventArgs) Handles Me.CloseUp
        _isDroppedDown = False
    End Sub

    Private Sub MyDateTimePicker_DropDown(sender As Object, e As System.EventArgs) Handles Me.DropDown
        _isDroppedDown = True
    End Sub

End Class

After the next build, the new MyDateTimePicker class should appear in your toolbox under the project's 'Components' tab. It will have all of the usual events, methods and properties associated with DateTimePickers, plus your new `.IsDroppedDown` property.

Oh and if it's something you use regularly you could create it as a new class library and simply include the DLL it builds in your projects.

Problem

I'm needing to determine if the calendar dropdown is currently being shown in a WinForms DateTimePicker. I've got a custom control that inherits from DateTimePicker, and I'm handling the KeyDown event in order to do stuff with navigation keys, but I'd like to bypass that code if the calendar dropdown is open, so that the user can use their navigation keys there. With the ComboBox control, it is easy to use the `.DroppedDown` property to check if it's open, but DateTimePicker doesn't have a property like this. I'm currently doing the following: ``` Private _isDroppedDown As Boolean = False Private Sub MyDateTimePicker_CloseUp(sender As Object, e As EventArgs) Handles Me.CloseUp _isDroppedDown = False End Sub Private Sub MyDateTimePicker_DropDown(sender As Object, e As EventArgs) Handles Me.DropDown _isDroppedDown = True End Sub ``` However, I'd like to know if there's a better way to get the DroppedDown state of the control than manually keeping track of it with a variable?

Original source