Highlighting Listbox Item when Mouseover on Item - vb.net

I manage to customize the normal list box with an image, change text and background color when item is selected in ownerdrawn, what I want to achieve now is to drawn a custom highlight color on the item when mouse is hover on the listbox item, is that possible or not..., I provided my sample code below on what I come so far..
If e.Index = -1 Then Exit Sub
Dim listBox As ListBox = CType(sender, ListBox)
e.DrawBackground()
Dim isItemSelected As Boolean = ((e.State And DrawItemState.Selected) = DrawItemState.Selected)
If e.Index >= 0 AndAlso e.Index < listBox.Items.Count Then
Dim textSize As SizeF = e.Graphics.MeasureString(listBox.Items(e.Index).ToString(), listBox.Font)
Dim itemImage As Image = My.Resources.FolderHorizontal
'set background and text color
Dim backgroundColorBrush As New SolidBrush(If((isItemSelected), Color.CornflowerBlue, Color.White))
Dim itemTextColorBrush As Color = If((isItemSelected), Color.White, Color.Black)
e.Graphics.FillRectangle(backgroundColorBrush, e.Bounds)
'draw the item image
e.Graphics.SmoothingMode = SmoothingMode.HighQuality
e.Graphics.DrawImage(itemImage, e.Bounds.X + 2, _
e.Bounds.Y + (e.Bounds.Height - textSize.Height) / 2, _
itemImage.Width, itemImage.Height)
'draw the item text
Dim x, y As Single
Dim h As Single = textSize.Height
Dim rect As Rectangle = e.Bounds
rect.X += listBox.ItemHeight
rect.Width -= listBox.ItemHeight
x = rect.X - 3
y = rect.Y + (rect.Height - h) / 2
Dim itemText As String = listBox.Items(e.Index).ToString()
TextRenderer.DrawText(e.Graphics, itemText, e.Font, _
New Rectangle(x, y, ClientRectangle.Width, ClientRectangle.Height), _
itemTextColorBrush, TextFormatFlags.Default)
'clean up
backgroundColorBrush.Dispose()
End If
e.DrawFocusRectangle()

You can use the IndexFromPoint to do something like that:
Dim mouseIndex As Integer = -1
Private Sub ListBox1_MouseMove(sender As Object, e As MouseEventArgs) _
Handles ListBox1.MouseMove
Dim index As Integer = ListBox1.IndexFromPoint(e.Location)
If index <> mouseIndex Then
If mouseIndex > -1 Then
Dim oldIndex As Integer = mouseIndex
mouseIndex = -1
If oldIndex <= ListBox1.Items.Count - 1 Then
ListBox1.Invalidate(ListBox1.GetItemRectangle(oldIndex))
End If
End If
mouseIndex = index
If mouseIndex > -1 Then
ListBox1.Invalidate(ListBox1.GetItemRectangle(mouseIndex))
End If
End If
End Sub
Then in your drawing code:
If mouseIndex > -1 AndAlso mouseIndex = e.Index Then
backgroundColorBrush = New SolidBrush(Color.DarkMagenta)
End If

I will show you how to do this. All experts say its complicated and cannot be done with a listbox... I was able to do that in 5 minutes
the name of the listbox I created is listPOSSIBILITIES
1) create a variable which is global to your form
Dim HOVERTIME As Boolean = True
2) create MouseEnter event
Private Sub listPOSSIBILITIES_MouseEnter(sender As Object, e As system.EventArgs) Handles listPOSSIBILITIES.MouseEnter
HOVERTIME = True
End Sub
3) create MouseLeave event
Private Sub listPOSSIBILITIES_MouseLeave(sender As Object, e As System.EventArgs) Handles listPOSSIBILITIES.MouseLeave
HOVERTIME = False
End Sub
4) create MouseMove event
Private Sub listPOSSIBILITIES_MouseMove(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles listPOSSIBILITIES.MouseMove
Dim mypoint As Point
mypoint = listPOSSIBILITIES.PointToClient(Cursor.Position)
Dim myindex As Integer = listPOSSIBILITIES.IndexFromPoint(mypoint)
If myindex < 0 Then Exit Sub
listPOSSIBILITIES.SelectedIndex = myindex
End Sub
5) create MouseClick event
Private Sub listPOSSIBILITIES_MouseClick(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles listPOSSIBILITIES.MouseClick
HOVERTIME = False
End Sub
6) create SelectedIndexChanged event
Private Sub listPOSSIBILITIES_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles listPOSSIBILITIES.SelectedIndexChanged
If HOVERTIME Then Exit Sub
'put the rest of your code after this above If statement
End Sub
This works because the MouseClick event is triggered before the SelectIndexChanged event

Related

ListView: MultiSelect items with mouse drag

In ListView, I can press Ctrl + Shift and click on the item to select. But, I want to drag the mouse to select the items (like DataGridView). I tried this code (below) and I had a problem like this:
My code:
Private mouseDownLV As Boolean
Private Sub ListView1_MouseDown(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles ListView1.MouseDown
mouseDownLV = True
End Sub
Private Sub ListView1_MouseMove(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles ListView1.MouseMove
If mouseDownLV Then
Try
Dim i = ListView1.HitTest(e.Location).Item.Index
ListView1.Items(i).Selected = True
Catch ' ex As Exception
End Try
End If
End Sub
Private Sub ListView1_MouseUp(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles ListView1.MouseUp
mouseDownLV = False
End Sub
Actually you need to iterate through the currently displayed ListViewItem objects and toggle the Selected property of the items that intersect with the mouse movement. Here's a way to achieve that:
Declare a class member named startPoint:
Private startPoint As Point
Handle the MouseDown event to set the starting position:
Private Sub ListView1_MouseDown(sender As Object, e As MouseEventArgs) Handles ListView1.MouseDown
Dim s = DirectCast(sender, ListView)
If e.Button = MouseButtons.Left AndAlso
s.Items.Count > 1 Then
startPoint = e.Location
End If
End Sub
Handle the MouseMove event to toggle the Selected property:
Private Sub ListView1_MouseMove(sender As Object, e As MouseEventArgs) Handles ListView1.MouseMove
Dim s = DirectCast(sender, ListView)
If e.Button = MouseButtons.Left AndAlso s.Items.Count > 1 Then
Dim selRect As New Rectangle(Math.Min(startPoint.X, e.Location.X),
Math.Min(startPoint.Y, e.Location.Y),
Math.Abs(e.Location.X - startPoint.X),
Math.Abs(e.Location.Y - startPoint.Y))
Dim cr = s.ClientRectangle
'Toggle selection...
For Each item In s.Items.Cast(Of ListViewItem).
Where(Function(x) x.Bounds.IntersectsWith(cr))
item.Selected = selRect.IntersectsWith(item.Bounds)
Next
End If
End Sub
A quick demo to check that:
But what if you have many items where the size of the client area is not large enough to display them all and thus the vertical scrollbar is visible? You will get something like this:
As you can see, the vertical scrollbar does not move and you won't be able to continue selecting/deselecting the hidden items. To fix that, we need some more code:
Import the signature of the GetScrollPos function somewhere in your class:
Imports System.Runtime.InteropServices
'...
<DllImport("user32.dll", CharSet:=CharSet.Auto)>
Private Shared Function GetScrollPos(hWnd As IntPtr,
nBar As Orientation) As Integer
End Function
Note: Passing a System.Windows.Forms.Orientation value instead of an Interger.
Change the MouseDown event to:
Private Sub ListView1_MouseDown(sender As Object, e As MouseEventArgs) Handles ListView1.MouseDown
Dim s = DirectCast(sender, ListView)
If e.Button = MouseButtons.Left AndAlso
s.Items.Count > 1 Then
Dim vsp = GetScrollPos(s.Handle, Orientation.Vertical)
Dim yOffset = s.Font.Height * vsp
startPoint = New Point(e.X, e.Y + yOffset)
End If
End Sub
And the MouseMove event to:
Private Sub ListView1_MouseMove(sender As Object, e As MouseEventArgs) Handles ListView1.MouseMove
Dim s = DirectCast(sender, ListView)
If e.Button = MouseButtons.Left AndAlso s.Items.Count > 1 Then
Dim vsp = GetScrollPos(s.Handle, Orientation.Vertical)
Dim yOffset = s.Font.Height * vsp
Dim selRect As New Rectangle(Math.Min(startPoint.X, e.Location.X),
Math.Min(startPoint.Y - yOffset, e.Location.Y),
Math.Abs(e.Location.X - startPoint.X),
Math.Abs(e.Location.Y - startPoint.Y + yOffset))
Dim cr = s.ClientRectangle
'Toggle selection...
For Each item In s.Items.Cast(Of ListViewItem).
Where(Function(x) x.Bounds.IntersectsWith(cr))
item.Selected = selRect.IntersectsWith(item.Bounds)
Next
'Scroll if needed...
Dim p = s.PointToClient(Cursor.Position)
Dim lvi = s.GetItemAt(p.X, p.Y)
If lvi Is Nothing Then Return
Dim fh = s.Font.Height
If lvi.Index > 0 AndAlso (p.Y - lvi.Bounds.Height * 1.5) <= fh Then
s.Items(lvi.Index - 1).EnsureVisible()
ElseIf lvi.Index < s.Items.Count - 1 AndAlso
(p.Y + lvi.Bounds.Height * 1.5) > (s.Height - fh) Then
s.Items(lvi.Index + 1).EnsureVisible()
End If
End If
End Sub
The outcome is:
Here is VB.NET custom ListView control for this problem, and another in C#.

A Graphics object cannot be created from an image that has an indexed pixel format

I have a program that when you click on picturebox1, it transfers the image inside it to picturebox2. Then I have an interpolation code to modify it to a nearestneighbor pixel rendering. It also draws a pixel grid on picturebox2 to line up around the pixels. I have picturebox2 set to stretch image. I tried 2 different methods of drawing on the picturebox2. I am having a problem converting the image back to the right size to transfer it back to picturebox1 after its been edited with the paintbrush.
CODE:
Imports System.Windows.Forms
Imports System.Drawing
Imports System
Imports System.IO
Public Class Form1
Dim Brush = Brushes.Black
Dim COLOR1 As Color
Dim BMP As Bitmap
Dim Draw As Boolean
CODE: when you click on the picturebox1(topleft) it transfers its image to picturebox2(canvaseditor) does the grid draw, interpolate mode etc.
Private Sub topleft_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles topleft.Click
tiledcanvas.BackgroundImage = topleft.Image
Label1.Text = "Top-Left"
'CANVAS PIXEL GRID CODE
If topleft.Image Is Nothing Then
Else
canvaseditor.Image = Nothing
canvaseditor.Image = topleft.Image
canvaseditor.Width = topleft.Width * 8 + 1
canvaseditor.Height = topleft.Height * 8 + 1
'load and draw the image(s) once
BackgroundImage1 = New Bitmap(topleft.Image)
bmpNew = New Bitmap(canvaseditor.Width * scaleFactor, canvaseditor.Height * scaleFactor)
Using g As Graphics = Graphics.FromImage(bmpNew)
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor
g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.Half
g.DrawImage(BackgroundImage1, 0, 0, bmpNew.Width, bmpNew.Height)
End Using
canvaseditor.Focus()
GroupBox13.Focus()
End If
End Sub
CODE: the paintbrush code, the mousedown, mousemove, and mouseup events on picturebox2(canvaseditor)
Private Sub canvaseditor_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles canvaseditor.MouseMove
If Draw = True Then
PaintBrush(e.X, e.Y)
Else
End If
'If down = True Then
'canvaseditor.CreateGraphics.FillRectangle(Brush, e.X, e.Y, 8, 8)
'End If
' LocalMousePosition = canvaseditor.PointToClient(Cursor.Position)
'Dim X As Integer
'Dim Y As Integer
'If LocalMousePosition.X > 0 And LocalMousePosition.X < 9 Then
'X = 1
' ElseIf LocalMousePosition.X > 8 And LocalMousePosition.X < 17 Then
'X = 2
'ElseIf LocalMousePosition.X > 16 And LocalMousePosition.X < 25 Then
'X = 3
'End If
'Label6.Text = (X & ", " & Y)
End Sub
Private Sub PaintBrush(ByVal X As Integer, ByVal Y As Integer)
Using g As Graphics = Graphics.FromImage(canvaseditor.Image)
g.FillRectangle(New SolidBrush(Color.Black), New Rectangle(X, Y, 6, 6))
End Using
canvaseditor.Refresh()
End Sub
Private Sub canvaseditor_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles canvaseditor.MouseDown
'down = True
'If down = True Then
'Dim NEWBMP As New Bitmap(topleft.Width, topleft.Height)
'Dim graph As Graphics = Graphics.FromImage(NEWBMP)
' graph.FillRectangle(Brush, e.X, e.Y, 8, 8)
'topleft.Image = NEWBMP
'End If
'down = True
'If down = True Then
'canvaseditor.CreateGraphics.FillRectangle(Brush, e.X, e.Y, 8, 8)
'End If
Draw = True
PaintBrush(e.X, e.Y)
End Sub
Private Sub canvaseditor_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles canvaseditor.MouseUp
Draw = False
End Sub
and heres the first paint sub i made:
Private Sub canvaseditor_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles canvaseditor.Paint
If Not bmpNew Is Nothing Then
e.Graphics.DrawImage(bmpNew, 0, 0)
End If
Dim g As Graphics = e.Graphics
Dim pn As New Pen(Color.DimGray) '~~~ color of the lines
Dim x As Integer
Dim y As Integer
Dim intSpacing As Integer = 8 '~~~ spacing between adjacent lines
'~~~ Draw the horizontal lines
x = canvaseditor.Width
For y = 0 To canvaseditor.Height Step intSpacing
g.DrawLine(pn, New Point(0, y), New Point(x, y))
Next
'~~~ Draw the vertical lines
y = canvaseditor.Height
For x = 0 To canvaseditor.Width Step intSpacing
g.DrawLine(pn, New Point(x, 0), New Point(x, y))
Next
End Sub
hoping this is understandable so someone can point me in the right direction. thanks.

Resizing drawn rectangle on Picturebox relative to image using Zoom

I have a Picturebox that I can draw a rectangle on and I have it so that the rectangle dimensions, in percent, are logged so that if the size of the form changes, then so does the rectangle size (see code below the text)
However, when I have the Picturebox in "Zoom" mode, the rectangle does not match up when resizing (see here: First one, with corners on defined points on image http://i1262.photobucket.com/albums/ii602/bmgh85/Size1.png and then second one after resizing the form http://i1262.photobucket.com/albums/ii602/bmgh85/Size2.png
It works fine in "Stretch" mode, but that skews the images, which is no use to me (I need to keep the proportions). How can I manipulate my code to get it to work as intended?
Private x, y As Integer
Private Rct As New Rectangle(0, 0, 0, 0)
Private Sub PictureBox1_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles PictureBox1.MouseDown
If e.Button = Windows.Forms.MouseButtons.Left Then
x = e.X
y = e.Y
End If
End Sub
Private Sub PictureBox1_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles PictureBox1.MouseMove
If e.Button = Windows.Forms.MouseButtons.Left Then
Rct.X = Math.Min(x, e.X)
Rct.Y = Math.Min(y, e.Y)
Rct.Height = Math.Abs(e.Y - y)
Rct.Width = Math.Abs(e.X - x)
PictureBox1.Refresh()
PictureBox1.Tag = calculatePercent(Rct.X, Rct.Y, Rct.Height, Rct.Width, PictureBox1)
End If
End Sub
Private Sub PictureBox1_MouseUp(sender As Object, e As MouseEventArgs) Handles PictureBox1.MouseUp
MsgBox(PictureBox1.Tag)
Dim lst1 As List(Of Int32) = returnPercent(PictureBox1.Tag)
For i = 0 To lst1.Count - 1
MsgBox(lst1(i))
Next
End Sub
Private Sub PictureBox1_Paint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles PictureBox1.Paint
e.Graphics.DrawRectangle(Pens.Red, Rct)
End Sub
Function calculatePercent(ByVal X As Long, Y As Long, Ht As Long, Wth As Long, pBox As PictureBox)
Dim wPercent As Long = 100 * Wth / pBox.Width
Dim hPercent As Long = 100 * Ht / pBox.Height
Dim yPercent As Long = 100 * Y / pBox.Height
Dim xPercent As Long = 100 * X / pBox.Width
Return "X:" & xPercent & ", Y:" & yPercent & ", Ht:" & hPercent & ", Wth:" & wPercent
End Function
Function returnPercent(ByVal myTag As String)
Dim lst As New List(Of Int32)
Dim getX As String = getNum(Mid(myTag, InStr(myTag, "X:"), InStr(myTag, ", Y:") - InStr(myTag, "X:")))
Dim getY As String = getNum(Mid(myTag, InStr(myTag, ", Y:"), InStr(myTag, ", Ht:") - InStr(myTag, ", Y:")))
Dim getH As String = getNum(Mid(myTag, InStr(myTag, ", Ht:"), InStr(myTag, ", Wth:") - InStr(myTag, ", Ht:")))
Dim getW As String = getNum(Mid(myTag, InStr(myTag, ", Wth:")))
lst.Add(getX)
lst.Add(getY)
lst.Add(getH)
lst.Add(getW)
Return lst
End Function
Function getNum(ByVal txt As String)
Dim rtn As String = vbNullString
Dim coln As MatchCollection = Regex.Matches(txt, "\d+")
For Each mtch As Match In coln
rtn = rtn & mtch.ToString
Next
Return Convert.ToInt32(rtn)
End Function
Private Sub PictureBox1_SizeChanged(sender As Object, e As EventArgs) Handles PictureBox1.SizeChanged
Dim lst As New List(Of Int32)
If PictureBox1.Tag <> "" Then
lst = returnPercent(PictureBox1.Tag)
Rct.X = lst(0) * PictureBox1.Width / 100
Rct.Y = lst(1) * PictureBox1.Height / 100
Rct.Height = lst(2) * PictureBox1.Height / 100
Rct.Width = lst(3) * PictureBox1.Width / 100
PictureBox1.Refresh()
End If
End Sub
I have some code that might help you:
' Rectangle to draw
Private Rct As New Rectangle(0, 0, 0, 0)
Private offsetX As Integer = 0
Private offsetY As Integer = 0
Sub Main() Handles MyBase.Load
' Some image to use
MiniPictureBox.Image = My.Resources.P6130003
MainPictureBox.Image = My.Resources.P6130003
End Sub
Private Sub MiniPictureBox_MouseDown(sender As Object, e As MouseEventArgs) Handles MiniPictureBox.MouseDown
If e.Button = Windows.Forms.MouseButtons.Left Then
If Not Rct.Contains(e.Location) Then
' New rectangle
Rct.Location = New Point(e.X, e.Y)
Else
' Moving a rectangle
offsetX = Rct.X - e.X
offsetY = Rct.Y - e.Y
End If
ElseIf e.Button = Windows.Forms.MouseButtons.Right Then
' Clears the screen of a rectangle
Rct = New Rectangle(0, 0, 0, 0)
MiniPictureBox.Invalidate()
End If
End Sub
Private Sub MiniPictureBox_MouseMove(sender As Object, e As MouseEventArgs) Handles MiniPictureBox.MouseMove
' Event handler to update the picture of the rectangle
If e.Button = Windows.Forms.MouseButtons.Left Then
If Rct.Contains(e.Location) Then
' Move the box
Rct.X = e.X + offsetX
Rct.Y = e.Y + offsetY
MainPictureBox.Invalidate()
Else
' Update the size of the box
Rct.Width = e.X - Rct.X
Rct.Height = e.Y - Rct.Y
End If
MiniPictureBox.Invalidate()
End If
End Sub
Private Sub MiniPictureBox_MouseUp(sender As Object, e As MouseEventArgs) Handles MiniPictureBox.MouseUp
' Event handler to call the paint event for runtime display
MiniPictureBox.Invalidate()
MainPictureBox.Invalidate()
End Sub
Private Sub MiniPictureBox_Paint(sender As Object, e As PaintEventArgs) Handles MiniPictureBox.Paint
Dim myPen As Pen = New Pen(Brushes.Red, 2)
e.Graphics.DrawRectangle(myPen, Rct)
End Sub
Private Sub MainPictureBox_Paint(sender As Object, e As PaintEventArgs) Handles MainPictureBox.Paint
If Rct.Width > 0 Then
Dim biggerRec As Rectangle = CalculateRectangle(MainPictureBox)
Dim myPen As Pen = New Pen(Brushes.Red, 2)
e.Graphics.DrawRectangle(myPen, biggerRec)
End If
End Sub
Private Function CalculateRectangle(currentPicture As PictureBox) As Rectangle
Try
Dim newWidth As Integer = (Rct.Width / MiniPictureBox.Width) * currentPicture.Image.Width
Dim newHeight As Integer = (Rct.Height / MiniPictureBox.Height) * currentPicture.Image.Height
Dim newX As Integer = (Rct.X / MiniPictureBox.Width) * currentPicture.Image.Width
Dim newY As Integer = (Rct.Y / MiniPictureBox.Height) * currentPicture.Image.Height
Return New Rectangle(newX, newY, newWidth, newHeight)
Catch ex As Exception
MessageBox.Show(ex.Message + Environment.NewLine + Environment.NewLine + ex.StackTrace)
End Try
End Function
This code will allow you to create, move, and clear a rectangle. One point of caution is in the calculations for changing the size of the rectangle, you have to ensure exception handling is properly inserted for any arithmetic exceptions.

Control Not move in drag and drop

In my Application i want to move the control one side another side. That control inside the tablelayoutpanel. I would like to drag the control which is inside the panel and the panel is inside the table layout panel so first i remove the control form panel and add the control in form after that i drag the button control its make the issue not clearly dragging. (that means drag fast its not working properly). My Code is
Private Sub HandleDraggableControlMouseDown(ByVal sender As Object, ByVal e As MouseEventArgs) Handles Button2.MouseDown
Dim target As Control = TryCast(sender, Control)
Dim xWidth, xHeight As Integer
If (Not target Is Nothing) Then
xWidth = sender.Width
xHeight = sender.Height
sender.Parent.Controls.Remove(sender)
sender.Dock = DockStyle.None
sender.Width = xWidth
sender.Height = xHeight
Me.Controls.Add(sender)
Dim pt As Point = Me.PointToClient(target.PointToScreen(Point.Empty))
target.Location = pt
target.Parent = Me
target.BringToFront()
Me.isMouseDown = True
Me.cachedControlPos = pt
Me.cachedMousePos = Control.MousePosition
End If
End Sub
Private Sub HandleDraggableControlMouseMove(ByVal sender As Object, ByVal e As MouseEventArgs) Handles Button2.MouseMove
If (Me.isMouseDown) Then
Dim target As Control = TryCast(sender, Control)
If (Not target Is Nothing) Then
Dim x As Integer = (Me.cachedControlPos.X + (Control.MousePosition.X - Me.cachedMousePos.X))
Dim y As Integer = (Me.cachedControlPos.Y + (Control.MousePosition.Y - Me.cachedMousePos.Y))
target.Location = New Point(x, y)
'c2 = (c1 + (m2 - m1))
End If
End If
End Sub
Private Sub HandleDraggableControlMouseUp(ByVal sender As Object, ByVal e As MouseEventArgs) Handles Button2.MouseUp
Me.cachedControlPos = Point.Empty
Me.cachedMousePos = Point.Empty
Me.isMouseDown = False
End Sub
My problem is if drag the control fast the control not moved cursor only moved why?. What am doing wrong in my coding?. How is solve the problem?
You need to add the difference between the current mouse position m2 and the cached mouse position m1 to a cached control position c1 to give you the current control position c2.
c2 = (c1 + (m2 - m1))
Something like this:
sender.Location = New Point(
(cachedControlLocation.X + (e.X - startX)),
(cachedControlLocation.Y + (e.Y - startY))
)
Here's a sample form to show you how it works:
Public Class Form1
Public Sub New()
Me.InitializeComponent()
Me.ClientSize = New Size(800, 600)
Me.panel1 = New Panel() With {.Bounds = New Rectangle(10, 10, 300, 300), .BackColor = Color.Red}
Me.panel2 = New Panel() With {.Bounds = New Rectangle(10, 10, 200, 200), .BackColor = Color.Green}
Me.panel3 = New Panel() With {.Bounds = New Rectangle(10, 10, 100, 100), .BackColor = Color.Blue}
Me.panel2.Controls.Add(Me.panel3)
Me.panel1.Controls.Add(Me.panel2)
Me.Controls.Add(Me.panel1)
End Sub
Private Sub HandleDraggableControlMouseDown(sender As Object, e As MouseEventArgs) Handles panel1.MouseDown, panel2.MouseDown, panel3.MouseDown
Dim target As Control = TryCast(sender, Control)
If (Not target Is Nothing) Then
Dim pt As Point = Me.PointToClient(target.PointToScreen(Point.Empty))
target.Parent = Me
target.BringToFront()
target.Location = pt
Me.isMouseDown = True
Me.cachedControlPos = pt
Me.cachedMousePos = Control.MousePosition
End If
End Sub
Private Sub HandleDraggableControlMouseMove(sender As Object, e As MouseEventArgs) Handles panel1.MouseMove, panel2.MouseMove, panel3.MouseMove
If (Me.isMouseDown) Then
Dim target As Control = TryCast(sender, Control)
If (Not target Is Nothing) Then
Dim x As Integer = (Me.cachedControlPos.X + (Control.MousePosition.X - Me.cachedMousePos.X))
Dim y As Integer = (Me.cachedControlPos.Y + (Control.MousePosition.Y - Me.cachedMousePos.Y))
target.Location = New Point(x, y)
'c2 = (c1 + (m2 - m1))
End If
End If
End Sub
Private Sub HandleDraggableControlMouseUp(sender As Object, e As MouseEventArgs) Handles panel1.MouseUp, panel2.MouseUp, panel3.MouseUp
Me.cachedControlPos = Point.Empty
Me.cachedMousePos = Point.Empty
Me.isMouseDown = False
End Sub
Private cachedMousePos As Point
Private cachedControlPos As Point
Private isMouseDown As Boolean
Private WithEvents panel1 As Panel
Private WithEvents panel2 As Panel
Private WithEvents panel3 As Panel
End Class
Update 1
It's important that you set the new location after you've changed the parent and moved it to the front.
target.Parent = Me
target.BringToFront()
target.Location = pt '<---
Update 2
So I've narrowed it down to what's causing this issue, and it turns out to be the Selectable control style. You can verify this by subclassing the button class and remove the style in the constructor.
Public Class UIButton
Inherits Button
Public Sub New()
MyBase.SetStyle(ControlStyles.Selectable, False)
End Sub
End Class
So how can we fix this? Well, AFAIK there's no easy solution. It's to be expected that a selectable control will process the mouse messages in a different way than those who can't. The only way I can think of (and it might be a dirty one) is to subclass the control(s) and intercept the mouse messages. The following code is not a final solution, so use it with caution.
Public Class UIButton
Inherits Button
Protected Overrides Sub WndProc(ByRef m As Message)
Select Case m.Msg
Case WM.LBUTTONDOWN
Dim dw As New DWORD With {.value = m.LParam}
Dim vk As Integer = m.WParam.ToInt32()
MyBase.OnMouseDown(New MouseEventArgs(Windows.Forms.MouseButtons.Left, 0, dw.loword, dw.hiword, 0))
Debug.WriteLine("X={0}, Y={1}", dw.loword, dw.hiword)
Exit Select
Case WM.MOVE
Dim dw As New DWORD With {.value = m.LParam}
Dim vk As Integer = m.WParam.ToInt32()
If (vk = Keys.LButton) Then
MyBase.OnMouseMove(New MouseEventArgs(Windows.Forms.MouseButtons.Left, 0, dw.loword, dw.hiword, 0))
Debug.WriteLine("X={0}, Y={1}", dw.loword, dw.hiword)
End If
Exit Select
Case WM.LBUTTONUP
Dim dw As New DWORD With {.value = m.LParam}
Dim vk As Integer = m.WParam.ToInt32()
MyBase.OnMouseUp(New MouseEventArgs(Windows.Forms.MouseButtons.Left, 0, dw.loword, dw.hiword, 0))
Debug.WriteLine("X={0}, Y={1}", dw.loword, dw.hiword)
Exit Select
End Select
MyBase.WndProc(m)
End Sub
Private Enum WM As Integer
MOVE = &H200
LBUTTONDOWN = &H201
LBUTTONUP = &H202
End Enum
<StructLayout(LayoutKind.Explicit)> _
Private Structure DWORD
<FieldOffset(0)> Public value As Integer
<FieldOffset(0)> Public loword As Short
<FieldOffset(2)> Public hiword As Short
End Structure
End Class

How to draw points when user clicks on a map

Dim HaveToDraw As New Boolean
Dim xMouse As Integer
Dim yMouse As Integer
Private Sub foo(sender As Object, e As PaintEventArgs) Handles PictureBox1.Paint
If HaveToDraw = True Then
e.Graphics.FillEllipse(Brushes.Green, xMouse, yMouse, 10, 10)
End If
HaveToDraw = False
End Sub
Sub PictureBox1_MouseClick(sender As Object, e As MouseEventArgs) Handles PictureBox1.MouseClick
If RadioButton1.Checked = True Then
xMouse = e.X
yMouse = e.Y
HaveToDraw = True
PictureBox1.Refresh()
End If
End Sub
This code lets the user draw an elipse when he clicks on any point on the map, but there are 2 problems with it: 1 - The user is able to draw only one elipse; 2 - The user is not able to erase a previously created elipse.
So, how can I do that solving these two problems?
As #Idle_Mind suggested, you could use a list to store your points, and a right-click event to remove the points:
Dim radius as Integer = 5
Private points As New List(Of Point)()
Private Sub pictureBox1_MouseClick(sender As Object, e As MouseEventArgs)
If e.Button = System.Windows.Forms.MouseButtons.Left Then
points.Add(e.Location) ' add point on left click
ElseIf e.Button = System.Windows.Forms.MouseButtons.Right Then
For i As Integer = 0 To points.Count - 1 ' remove points on right-click
If distance(points(i).X, points(i).Y, e.Location) < radius Then
points.RemoveAt(i)
End If
Next
End If
pictureBox1.Refresh()
End Sub
'helper function
Private Function distance(x__1 As Integer, y__2 As Integer, mousep As Point) As Integer
Dim X__3 As Integer = CInt(Math.Pow(CDbl(x__1 - mousep.X), 2))
Dim Y__4 As Integer = CInt(Math.Pow(CDbl(y__2 - mousep.Y), 2))
Return CInt(Math.Sqrt(CDbl(X__3 + Y__4)))
End Function
Private Sub pictureBox1_Paint(sender As Object, e As PaintEventArgs)
For i As Integer = 0 To points.Count - 1
e.Graphics.FillEllipse(Brushes.Green, points(i).X - radius, points(i).Y - radius, radius * 2, radius * 2)
Next
End Sub
I also changed the paint code to draw the circles so that they are centered under the mouse-click.