子事件与多个控件交互

时间:2012-12-18 10:49:07

标签: vb.net events arguments controls sender

我想将此片段称为“控制名称”,如同参数,然后子与所需控件交互

我怎么能这样做?

这是片段:

#Region " Move a control in real-time "
    ' Change Textbox1 to the desired control name
    Private Sub TextBox1_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles textbox1.MouseDown
        If e.Button = Windows.Forms.MouseButtons.Left Then
            textbox1.Capture = False
            Dim ControlMoveMSG As Message = Message.Create(textbox1.Handle, &HA1, New IntPtr(2), IntPtr.Zero)
            Me.DefWndProc(ControlMoveMSG)
        End If
    End Sub
#End Region

更新: 解决方案:

Private Sub MoveControl(sender As Object, e As EventArgs) Handles _
        TextBox1.MouseDown, _
        TextBox2.MouseDown, _
        PictureBox1.MouseDown

    Dim control As Control = CType(sender, Control)
    control.Capture = False
    Dim ControlMoveMSG As Message = Message.Create(control.Handle, &HA1, New IntPtr(2), IntPtr.Zero)
    Me.DefWndProc(ControlMoveMSG)
End Sub

1 个答案:

答案 0 :(得分:1)

在这种情况下,您只需使用sender即可。 sender参数是对引发事件的控件的引用。因此,如果您将此方法添加为多个控件的事件处理程序,sender将控制它引发当前正在处理的事件,例如:

Private Sub MouseDown(sender As Object, e As EventArgs) _
        Handles TextBox1.MouseDown, TextBox2.MouseDown
    ' Note in the line above that this method handles the event 
    ' for TextBox1 and TextBox2
    Dim textBox As TextBox = CType(sender, TextBox)
    ' textBox will now be either TextBox1 or TextBox2, accordingly
    textBox.Capture = False
    ' ....
End Sub

CType语句将基本Object参数强制转换为特定的TextBox类。在此示例中,该方法仅处理TextBox个对象的事件,因此可以使用。但是,如果您处理来自其他类型控件的事件,则需要转换为更通用的Control类型(即CType(sender, Control))。