Detect when a Combo Box Drops Down or Closes Up

This tip demonstrates how to detect a Combo Box drop down or close up by using subclassing. You will need to have installed and registered the Subclassing and Timer Assistant, available from this site at Subclassing without the crashes to run this sample.

Start a new project and choose Project-References. For VB5, you want the item "Subclassing and Timer Assistant (with multiple control support and timer bug fix)" in the references list; for VB6 you want "vbAccelerator VB6 Subclassing and Timer Assistant". If it is there, select it and click ok. If it isn't, choose Browse and locate either SSubTmr.DLL (VB5) or SSubTmr6.DLL (VB6) on your disk, then select it.

Then add a label control and a few combo boxes and add the following code to the form:

Option Explicit

Implements ISubclass

Private Const WM_COMMAND = &H111
Private Const CBN_DROPDOWN = 7
Private Const CBN_CLOSEUP = 8
Private Declare Function GetDlgCtrlID Lib "user32" (ByVal hwnd As Long) As Long

Private Sub Form_Load()
   AttachMessage Me, Combo1.Container.hwnd, WM_COMMAND
End Sub

Private Sub Form_QueryUnload(Cancel As Integer, UnloadMode As Integer)
   DetachMessage Me, Combo1.Container.hwnd, WM_COMMAND
End Sub

Private Property Let ISubclass_MsgResponse(ByVal RHS As SSubTimer.EMsgResponse)
End Property

Private Property Get ISubclass_MsgResponse() As SSubTimer.EMsgResponse
   ISubclass_MsgResponse = emrPreprocess
End Property

Private Function ISubclass_WindowProc(ByVal hwnd As Long, ByVal iMsg As Long, ByVal wParam As Long, ByVal lParam As Long) As Long
   Dim lID As Long
   Dim iCode As Long
   Select Case iMsg
      If lParam <> 0 Then
         iCode = (wParam And &HFFFF0000) \ &H10000
         ' the id of controls created by VB is the index
         ' of the control in the form's control array plus 1
         lID = wParam And &HFFFF&
         If TypeOf Controls(lID - 1) Is ComboBox Then
            Select Case iCode
            Case CBN_DROPDOWN
               Label1.Caption = Controls(lID - 1).Name & " Drop Down"
            Case CBN_CLOSEUP
               Label1.Caption = Controls(lID - 1).Name & " Close Up"
            End Select
         End If
      End If
   End Select
End Function

Start the project. When a combo drops down or closes up, the label will be updated.

Note that the window handle to subclass is the container of the combo boxes. If you place a combo box on a PictureBox control, then the messages for that combo box get sent to the PictureNpx control rather than the form. If you are using this technique, make sure that you are subclassing for the WM_COMMAND message on all container objects by adding extra AttachMessage calls.