Wednesday, April 13, 2011

HowTo: Force calendar dropdown in .Net DateTimePicker control using VB.Net

Here is how to force to show-up, and activate, the dropdown calendar of the standard .Net DateTimePicker control, using VB.Net.
The sample code is tested on .Net 4.0, but should work on all .Net framework version.


Code Snippet
  1. Dim dateTimePickerControl As DateTimePicker
  2.  
  3. Private Declare Auto Function SendMessage Lib "user32.dll" (ByVal hWnd As IntPtr, ByVal msg As Integer, ByVal wParam As IntPtr, ByVal lParam As IntPtr) As IntPtr
  4.  
  5. Public Sub DropDownCalendar()
  6.     Const WM_LBUTTONDOWN As Int32 = &H201
  7.     Const WM_LBUTTONUP As Int32 = &H202
  8.  
  9.     Dim x As Integer = Me.dateTimePickerControl.Width - 10
  10.     Dim y As Integer = CInt(Me.dateTimePickerControl.Height / 2)
  11.     Dim lParam As Integer = x + y * &H10000
  12.  
  13.     'click down, adn show the calendar
  14.     SendMessage(Me.dateTimePickerControl.Handle, WM_LBUTTONDOWN, CType(1, IntPtr), CType(lParam, IntPtr))
  15.  
  16.     'click-up, and activate the calendar (without this the calendar is showed, but is not active, and doesen't works as expected)
  17.     SendMessage(Me.dateTimePickerControl.Handle, WM_LBUTTONUP, CType(1, IntPtr), CType(lParam, IntPtr))
  18. End Sub