0

我想调用这个片段传递一个像参数一样的“控件名称”,然后子与所需的控件交互

我怎么能这样做?

这是片段:

#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
4

1 回答 1

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))。

于 2012-12-18T11:53:44.013 回答