需要在程序运行时动态建立若干按钮,这些按钮将存放在一个ArrayList中,我如何才能相应这些按钮的事件?首先按钮个数是程序运行时动态确定的,所以无法在编码的时候为每个button写一个响应函数。请各位大虾不吝赐教。

解决方案 »

  1.   

    用控件数组即可,首先在桌面上画一个按钮,设置其index属性为0,添加按钮用load语句(Load Command1(i)),然后你处理按钮的click事件就可以了:
    Option ExplicitPrivate Sub Command1_Click(Index As Integer)
        Select Case Index
        Case 0
            MsgBox "0"
        Case 1
            MsgBox "1"
        End Select
    End SubPrivate Sub Form_Load()
       Dim i As Long
       For i = 1 To 4
            Load Command1(i)
            Command1(i).Visible = True
            Command1(i).Move 100, 100 + i * 600
        Next
    End Sub
      

  2.   

    1.定义一个通用接口事件.
    Private WithEvents Ev_COmobj As VBControlExtender 
    2.在动态添加COMMANDBUTTON时.设置每一个BUTTON的TAG属性:例如象INDEX一样1,2,3,4等.
    3.在窗体上放一个TIMER控件.设置Interval=50.
    4.写Timer
    Private Sub Timer1_Timer()
            If TypeName(Me.ActiveControl) = "COMMANDBUTTON" Then
              Set COmobj = Me.ActiveControl
            End If
    End Sub5.处理通用接口事件(判断是那一个按钮,可以用NAME或TAG属性).  Private Sub Ev_GridObj_ObjectEvent(Info As EventInfo)
            '/通用事件接口
            Select Case UCase$(Info.Name)
                   Case UCase$("MouseDown")
                        '处理MOUSEDOWN事件
                   Case UCase$("GotFocus")               Case UCase$("MouseUp")
                           '.........
                     Case UCase$("CLICK")
                           '.........   
            End Select
    End Sub
      

  3.   

    突然间想起...VB标准的EXE是不能用能用事件处理的..
    特更正如下:Dim WithEvents Ev_CommandButton As VB.CommandButton'跟踪当前活动的控件.
    Private Sub Timer1_Timer()
            If TypeName(Me.ActiveControl) = "COMMANDBUTTON" Then
              Set CommandButton= Me.ActiveControl
            End If
    End Sub'处理单击事件.
    Private Sub Ev_CommandButton_Clcik()
             dim SelStr as string 
             selstr=ev_commandbutton.tag '.name
             select case selstr
                     case is="1"
                     case is="2"
             end select 
    End Sub..............................
      

  4.   


    唉!又写错了一条...更正一下:Private Sub Timer1_Timer()
            If TypeName(Me.ActiveControl) = "COMMANDBUTTON" Then
              Set ev_commandbutton= Me.ActiveControl
            End If
    End Sub
      

  5.   

    用AddHandler 解决了,多谢各位