Event to detect item added to ComboBox

后端 未结 4 1720
广开言路
广开言路 2021-01-23 17:37

I am creating a custom control that inherits from ComboBox. I need to detect when a Item is added to the ComboBox to perform my own checks. It doesn\'t matter if it\'s C# or Vb.

4条回答
  •  后悔当初
    2021-01-23 18:27

    I think the best approach would be to listen for the native ComboBox messages:

    • CB_ADDSTRING
    • CB_INSERTSTRING
    • CB_DELETESTRING
    • CB_RESETCONTENT

    Don't be fooled by the word STRING, they are all fired whenever you add, insert or delete an item. So when the list is cleared.

    Public Class UIComboBox
        Inherits ComboBox
    
        Private Sub NotifyAdded(index As Integer)
        End Sub
    
        Private Sub NotifyCleared()
        End Sub
    
        Private Sub NotifyInserted(index As Integer)
        End Sub
    
        Private Sub NotifyRemoved(index As Integer)
        End Sub
    
        Protected Overrides Sub WndProc(ByRef m As Message)
            Select Case m.Msg
                Case CB_ADDSTRING
                    MyBase.WndProc(m)
                    Dim index As Integer = (Me.Items.Count - 1)
                    Me.NotifyAdded(index)
                    Exit Select
                Case CB_DELETESTRING
                    MyBase.WndProc(m)
                    Dim index As Integer = m.WParam.ToInt32()
                    Me.NotifyRemoved(index)
                    Exit Select
                Case CB_INSERTSTRING
                    MyBase.WndProc(m)
                    Dim index As Integer = m.WParam.ToInt32()
                    Me.NotifyAdded(If((index > -1), index, (Me.Items.Count - 1)))
                    Exit Select
                Case CB_RESETCONTENT
                    MyBase.WndProc(m)
                    Me.NotifyCleared()
                    Exit Select
                Case Else
                    MyBase.WndProc(m)
                    Exit Select
            End Select
        End Sub
    
        Private Const CB_ADDSTRING As Integer = &H143
        Private Const CB_DELETESTRING As Integer = &H144
        Private Const CB_INSERTSTRING As Integer = 330
        Private Const CB_RESETCONTENT As Integer = &H14B
    
    End Class
    

提交回复
热议问题