Voici un petit exemple non commenté puisque déjà expliqué ci-dessus.
Option Strict On
Public Class Form1
Dim WithEvents Conteneur As New Panel With {.Bounds New Rectangle(0, 0, 202, 202), .Parent Me, .BackColor = Color.LightSteelBlue, .BorderStyle = BorderStyle.FixedSingle}
Dim WithEvents Element As New PictureBox With {.Bounds New Rectangle(210, 80, 50, 50), .Parent Me, .BackColor = Color.Pink, .BorderStyle = BorderStyle.FixedSingle}
Dim PointOrigine As Point
Dim ListeRectangles As New List(Of Rectangle)
Dim ListeRectanglesPoses As New List(Of Rectangle)
Private Sub Element_MouseDown(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles Element.MouseDown
If e.Button = Windows.Forms.MouseButtons.Left Then
PointOrigine = New Point(e.X + Me.Left + SystemInformation.BorderSize.Width, _
e.Y + Me.Top + SystemInformation.CaptionHeight)
Element.BackColor = Color.Pink
End If
End Sub
Private Sub Element_MouseMove(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles Element.MouseMove
If e.Button = Windows.Forms.MouseButtons.Left Then
DirectCast(sender, PictureBox).Location = Point.Subtract(Cursor.Position, New Size(PointOrigine))
End If
End Sub
Private Sub Element_MouseUp(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles Element.MouseUp
For Each rect As Rectangle In ListeRectangles
Dim RectInter As Rectangle = Rectangle.Intersect(Element.Bounds, rect)
If RectInter.Width > 25 And RectInter.Height > 25 Then
If Not ListeRectanglesPoses.Contains(rect) Then
Element.Bounds = New Rectangle(rect.Left + 1, rect.Top + 1, 51, 51)
ListeRectanglesPoses.Add(rect)
Exit For
Else
Element.BackColor = Color.Red
End If
End If
Next
End Sub
Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load
Element.BringToFront()
For y As Integer = 0 To 3
For x As Integer = 0 To 3
Dim MonRectangle As Rectangle = New Rectangle(x * 50, y * 50, 50, 50)
ListeRectangles.Add(MonRectangle)
Next
Next
End Sub
Private Sub Conteneur_Paint(sender As Object, e As System.Windows.Forms.PaintEventArgs) Handles Conteneur.Paint
For Each rect As Rectangle In ListeRectangles
If ListeRectanglesPoses.Contains(rect) Then
e.Graphics.FillRectangle(Brushes.Gray, rect)
e.Graphics.DrawRectangle(Pens.Blue, rect)
Else
e.Graphics.DrawRectangle(Pens.Blue, rect)
End If
Next
End Sub
End Class