2015-01-08 53 views
-1

所以我的問題是,我想一次在窗體上有多個矩形。不過,我也希望這些矩形能夠被點擊並拖動到表單中。 這是我當前的代碼,用於單擊並拖動使用工具箱繪製到窗體上的矩形。單擊並拖動一個矩形的實現VB.NET

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 

這對一個矩形很好,但這需要使用工具箱將矩形預繪製到窗體上。

我想要的是通過單擊窗體上的按鈕來繪製矩形,並且新繪製的矩形也可以單擊並拖動到新的位置。

這可能嗎? 感謝您的幫助

回答

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