Hey everyone. I'm new to the forum and hope you can help me.
I have code that allows the user to drag a label anywhere around a form that works perfectly. I'm trying to create a new label class that allows me to apply this functionality to labels created at runtime. Here is what I've done (I'm new to custom controls). The result is that the label created at runtime moves but not smoothly. What am I doing wrong?
This is my betterLabel class.
My form has a button that creates a label using this class:
I have code that allows the user to drag a label anywhere around a form that works perfectly. I'm trying to create a new label class that allows me to apply this functionality to labels created at runtime. Here is what I've done (I'm new to custom controls). The result is that the label created at runtime moves but not smoothly. What am I doing wrong?
This is my betterLabel class.
VB.NET:
Public Class betterLabel
Inherits Label
' These will be our switches
Dim Go As Boolean
Dim LeftSet As Boolean
Dim TopSet As Boolean
' These will hold the mouse position
Dim HoldLeft As Integer
Dim HoldTop As Integer
' These will hold the offset of the mouse in the element
Dim OffLeft As Integer
Dim OffTop As Integer
Sub betterLabel_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles MyBase.MouseUp
Go = False
LeftSet = False
TopSet = False
End Sub
Sub betterLabel_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles MyBase.MouseDown
Go = True
End Sub
Sub betterLabel_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles MyBase.MouseMove
' Check if the mouse is down
If Go = True Then
' Set the mouse position
HoldLeft = (Control.MousePosition.X - Me.Left)
HoldTop = (Control.MousePosition.Y - Me.Top)
' Find where the mouse was clicked ONE TIME
If TopSet = False Then
OffTop = HoldTop - sender.Top
' Once the position is held, flip the switch
' so that it doesn't keep trying to find the position
TopSet = True
End If
If LeftSet = False Then
OffLeft = HoldLeft - sender.Left
' Once the position is held, flip the switch
' so that it doesn't keep trying to find the position
LeftSet = True
End If
' Set the position of the object
sender.Left = HoldLeft - OffLeft
sender.Top = HoldTop - OffTop
End If
End Sub
End Class
My form has a button that creates a label using this class:
VB.NET:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim l As New betterLabel()
l.AutoSize = True
l.Location = New System.Drawing.Point(61, 60)
l.Name = "Labelbetter"
l.Size = New System.Drawing.Size(39, 13)
l.TabIndex = 0
l.Text = "Labelbetter"
l.Capture = True
'l.Show()
Controls.Add(l)
End Sub