Pergunta

I want to call this snippet passing a "controlname" like a argument, then the sub interacts with the desired control

How I can do that?

This is the snippet:

#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

UPDATE: The solution:

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
Foi útil?

Solução

In this case, you can just use sender. The sender parameter is a reference to whichever control is raising the event. So, if you add this same method as an event handler for multiple controls, sender will be which ever control raised the event that it's currently handling, for instance:

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

The CType statement casts the base Object parameter to the specific TextBox class. In this example, the method only handles events for TextBox objects, so that will work. However, if you have it handle events from other types of controls, you'd need to cast to the more general Control type (i.e. CType(sender, Control)).

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top