在矩形VB.NET上单击并拖动实现

时间:2015-01-08 17:58:01

标签: vb.net draggable rectangles

所以我的问题是我希望一次在表单上有多个矩形。但是我也希望能够在表单上单击并拖动这些矩形。 这是我当前使用工具箱单击并拖动绘制到表单上的矩形的代码。

Public Class DragRectangle
Dim Go As Boolean
Dim LeftSet As Boolean
Dim TopSet As Boolean

Dim HoldLeft As Integer
Dim HoldTop As Integer

Dim OffLeft As Integer
Dim OffTop As Integer


Private Sub obj1_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles RectangleShape1.MouseUp
    Go = False
    LeftSet = False
    TopSet = False
End Sub

Private Sub obj1_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles RectangleShape1.MouseDown
    Go = True
End Sub

Private Sub obj1_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles RectangleShape1.MouseMove
    If Go = True Then
        HoldLeft = (Control.MousePosition.X - Me.Left)
        HoldTop = (Control.MousePosition.Y - Me.Top)
        If TopSet = False Then
            OffTop = HoldTop - sender.Top
            TopSet = True
        End If
        If LeftSet = False Then
            OffLeft = HoldLeft - sender.Left
            LeftSet = True
        End If
        sender.Left = HoldLeft - OffLeft
        sender.Top = HoldTop - OffTop
    End If
End Sub
End Class

这适用于一个矩形,但这需要使用工具箱将矩形预先绘制到表单上。

我想要的是通过单击表单上的按钮绘制矩形,也可以单击新绘制的矩形并将其拖动到新位置。

这可能吗? 谢谢你的帮助

1 个答案:

答案 0 :(得分:0)

工作示例:

Public Class Form1
  Private Property Rectangles As New List(Of DrgRectangle)
  Private Property curRect As DrgRectangle
  Private _x As Integer
  Private _y As Integer
  Private Sub loadme() Handles Me.Load
   'load the rectangle in list
    Rectangles.Add(New DrgRectangle With {.Rect = New Rectangle(20, 20, 20, 20)})
  End Sub

  Private Sub FormMouseDown(sender As Object, e As MouseEventArgs) Handles Me.MouseDown
    _x = e.X
    _y = e.Y
    For Each rect In Rectangles
      If rect.Rect.Contains(e.X, e.Y) Then
        curRect = rect
        Exit For
      End If
    Next
  End Sub

  Private Sub FormMouseMove(sender As Object, e As MouseEventArgs) Handles Me.MouseMove
    If e.Button = Windows.Forms.MouseButtons.Left Then
      If curRect IsNot Nothing Then
        curRect.Rect = New Rectangle(New Point(curRect.Rect.Location.X + (e.X - _x), curRect.Rect.Location.Y + (e.Y - _y)), curRect.Rect.Size)
        Me.Refresh()
      End If
    End If
    _x = e.X
    _y = e.Y
  End Sub

  Private Sub FormPaint(sender As Object, e As PaintEventArgs) Handles me.Paint
    For Each rect In Rectangles
      e.Graphics.DrawRectangle(Pens.Black, rect.Rect)
    Next
  End Sub
End Class

Public Class DrgRectangle
  Public Rect As New Rectangle
  'add more properties as needed
End Class