我有这些代码要随表单一起移动。
Public BeingDragged As Boolean = False
Public MouseDownX As Integer
Public MouseDownY As Integer
Private Sub Mouse_Down(sender As Object, e As MouseEventArgs)
If e.Button = MouseButtons.Left Then
BeingDragged = True
MouseDownX = e.X
MouseDownY = e.Y
End If
End Sub
Private Sub TopPanel_MouseUp(sender As Object, e As MouseEventArgs)
If e.Button = MouseButtons.Left Then
BeingDragged = False
End If
End Sub
Private Sub TopPanel_MouseMove(sender As Object, e As MouseEventArgs)
If BeingDragged = True Then
Dim tmp As Point = New Point()
tmp.X = Form.Location.X + (e.X - MouseDownX)
tmp.Y = Form.Location.Y + (e.Y - MouseDownY)
Form.Location = tmp
tmp = Nothing
End If
End Sub
但是,我如何使用它来移动程序创建的窗体。我尝试了AddHandler Top_Panel。带lambda和地址的MouseDown,但什么都不起作用。因为的地址必须没有括号,我不知道没有它我怎么能定义e为MouseEventArgs。提前谢谢。
刚刚回答问题时,我错误地使用了AddHandler
。此代码运行良好。还要感谢Hans Passant,继承Form
类并创建我自己派生的"MovableForm"类将是最好的解决方案。
Module Program
Sub Main()
Application.EnableVisualStyles()
Application.SetCompatibleTextRenderingDefault(False)
Dim Form As Form = New Form With {
.Size = New Size(100, 100),
.FormBorderStyle = FormBorderStyle.None
}
Dim BeingDragged As Boolean = False
Dim MouseDownX, MouseDownY As Integer
AddHandler Form.MouseDown, Sub(sender As Object, e As MouseEventArgs)
If e.Button = MouseButtons.Left Then
BeingDragged = True
MouseDownX = e.X
MouseDownY = e.Y
End If
End Sub
AddHandler Form.MouseUp, Sub(sender As Object, e As MouseEventArgs)
If e.Button = MouseButtons.Left Then
BeingDragged = False
End If
End Sub
AddHandler Form.MouseMove, Sub(sender As Object, e As MouseEventArgs)
If BeingDragged = True Then
Dim tmp As Point = New Point With {
.X = Form.Location.X + (e.X - MouseDownX),
.Y = Form.Location.Y + (e.Y - MouseDownY)
}
Form.Location = tmp
tmp = Nothing
End If
End Sub
Application.Run(Form)
End Sub
End Module