Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to dynamically create a label box after run time 4

Status
Not open for further replies.

ulchm

Programmer
May 22, 2007
23
CA
Hey guys, one of the clerks at work here just e-mailed me something that really boggled my mind. Asides from going web-based (not an option) I don't know how to do this.

They basically want to be able to add an object (went with label because that's basically what it is) after run time and be able to move that and position it within the bounds of panel.

This is as far as I got with it then I started scratching my head

Dim intWidth As Integer, intHeight As Integer
Dim Box1 As System.Windows.Forms.Label

intWidth = txtWidth.Text.ToString()
intHeight = txtHeight.Text.ToString()

Box1 = New System.Windows.Forms.Label
Box1.BackColor = System.Drawing.Color.Yellow
Box1.Size = New System.Drawing.Size(intWidth, intHeight)
Box1.Location = New System.Drawing.Point(216, 88)
Box1.Text = txtID.Text.ToString()




The above code executes but nothing happens, Im' sure I'm just missing something small, the next obstacle however is to allow them to move the label around, and create more then 1 (up to 50+)

Let me know any ideas you might have.
 
To add the label to the panel, you must add it to the panel.controls collection.

Once it's working, the next step is to be able to move the labels around the panel.... you must learn how to add event handlers at runtime; the web is full of examples on how to achieve this. For moving the labels, try handling the MouseDown and MouseMove events.


The following article can help you a little bit with event handlers in vb.net:



Hope it helps.

---
If gray hair is a sign of wisdom, then talk like a pirate ninja monkey if you get the time to get funky once a week.
Wo bu zhi dao !
 

You can try this code block:

Code:
' Class member
Friend WithEvents newLabel As System.Windows.Forms.Label

Me.newLabel = New System.Windows.Forms.Label
Me.newLabel.Location = New System.Drawing.Point(locationX, locationY)
Me.newLabel.Name = "newLabel"
Me.newLabel.Size = New System.Drawing.Size(sizeWidth, sizeHeight)

' you need this line to add label to form's control collection.
[b]Me.Controls.Add(Me.newLabel)[/b]

If you note, you missed the last line which adds the newly instantiated label to form's control collection.

I'll post you the code sample for moving labels in the container by user after my office time.

 
Ok,

so I've got it doing everything there, it still doesn't show up on the screen. I can't help but think there must be something else I'm missing.

And a major problem with hard coding the

' Class member
Friend WithEvents newLabel As System.Windows.Forms.Label

is that there can be anywhere from 10 to 100 of these labels on the screen at any given time, maybe my understanding is wrong about how all this .net stuff works but wouldn't that mean I have to add a number of the above lines into my class as well?


 
Put the above code in a loop and just reposition each label as necessary
 
Ok that's good to know then,

the above code as it is still doesn't work to display the label. When I run the method it seems to create the object, but won't display.
 
For the code above to work, assign text to the text property of newlabel.
 
Nice shot there, indeed you won't see the label if it doesn't have text or border!

---
If gray hair is a sign of wisdom, then talk like a pirate ninja monkey if you get the time to get funky once a week.
Wo bu zhi dao !
 

Hello ulchm, back from office.
Here are quick solutions to both of your problems:

A.
ulchm said:
so I've got it doing everything there, it still doesn't show up on the screen. I can't help but think there must be something else I'm missing.

You need to draw a border or assign some value to Text property of label to view it.

B.
ulchm said:
And a major problem with hard coding the

' Class member
Friend WithEvents newLabel As System.Windows.Forms.Label

is that there can be anywhere from 10 to 100 of these labels on the screen at any given time, maybe my understanding is wrong about how all this .net stuff works but wouldn't that mean I have to add a number of the above lines into my class as well?

If you need to reposition the labels at runtime and there is no need to raise/respond label events except MouseDown, MouseMove and MouseUp then code block at the end of this post will suffice you to move either 1 or 100 or 10000 labels.

So here is the code block for you. At 2:40am in the morning here and fter working for 16 hours in the office, I cannot write more better and cleaner code for you than this one.

Pre-requisites:
- Add a Form to your project and name it "Form3".
- Add a Button to that Form and name it "Button1"
- Copy and Paste the following code block in code editor.

Code:
Public Class Form3
	' Class variable that handles all (blind) instances of Label control.
	' Note that I omitted "WithEvents" keyword here.
	Private newLabel As System.Windows.Forms.Label

	' Class members to control dragging behavior.
	Private dragNow As Boolean
	Private mouseLocation As Point

	Private Sub Form3_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
		' Not dragging now.
		dragNow = False

		'Setting up the Form canvas.
		Me.Size = New Size(700, 500)
		Me.Button1.SetBounds(10, 10, 200, 25)
		Me.Button1.Text = "&Click me to instantiate new Labels"
	End Sub

	' You click this button to instantiate a new Label control and set initial properties.
	Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
		' Instantiate and set properties.
		Me.newLabel = New System.Windows.Forms.Label()
		Me.newLabel.Location = New System.Drawing.Point(30, 100)
		Me.newLabel.Name = "newLabel"
		Me.newLabel.Text = "I love you more than my computer sweetheart, but don't tell it to my computer..."
		Me.newLabel.AutoSize = True

		' Add generic handlers to handle these three mouse events.
		AddHandler Me.newLabel.MouseDown, AddressOf Label_GenericMouseDown
		AddHandler Me.newLabel.MouseMove, AddressOf Label_GenericMouseMove
		AddHandler Me.newLabel.MouseUp, AddressOf Label_GenericMouseUp

		' Add label to Form's control collection.
		Me.Controls.Add(Me.newLabel)
	End Sub

	' Handles generic MouseDown event for labels.
	Private Sub Label_GenericMouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)
		' Mr. Label, if left mouse button is down then get ready to be dragged.
		If e.Button = Windows.Forms.MouseButtons.Left Then
			dragNow = True
			mouseLocation = e.Location
		End If
	End Sub

	' Handles generic MouseMove event for labels.
	Private Sub Label_GenericMouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)
		If (dragNow = True) Then
			' This NO-MAGICAL little equation do the actual job.
			CType(sender, Label).Location -= mouseLocation - e.Location
		End If
	End Sub

	' Handles generic MouseUp event for labels.
	Private Sub Label_GenericMouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)
		' Now you can relax Mr. Label. Dragging is over now.
		If dragNow = True Then dragNow = False
	End Sub

End Class

Hope this will make your life easier and you don't need to boggle your mind.
 
Wow that was really helpful. Thank you so much, I know some of these days of Attachmate Macro Coding and misc other VBA there is no way I would be going home and jumping onto a site posting code like that.

As much as it pains me to do this to ya..

e.Location

MouseEventArgs doesn't have a location in my version of Visual Studio (2003)

I have an x,y and before I go ahead ripping this down implementing x,y into it I want to make sure that's the right thing to do and that I didn't just forget to include something etc. (sorry for this, but I'm a php guy, VB is not my forte)

 
Ok I'm really close now, I've got the label moving but it's doing some very strange ghosting effect...


I must've screwed up a bit when modifying the code but I can't see how as of yet.

By ghosting I mean I click and drag and I see the text moving (kind of it's a bit sketchy) but I also see it again 200px (aprox) above and 50px (aprox) to the left of where it was originally. so it's like I'm clicking and dragging 2.

But thanks again it's getting REALLY close now
 

that link has an image with what is going on the border that is almost all grey is the one I'm currently dragging, the top one that is yellow with black lines through it is the 'ghost' as I'm calling it.

whenever I click on a label to drag it. it draws a ghost in the top left corner of the screen, and it seems to alternate between dropping the ghost or the real label when I release the mouse button.
 

Dear ulchm,
Nice to know that you have almost solved your problem. Keep it up and never give up. Here is a quick trick to make your dragging flicker-free.

Code:
[COLOR=green]
' NOTE: Only change the following lines in my above mentioned code block.
' Actual line is commented followed by new line of code.
' All other lines will remain same.

' Changes in Class member
[b]
' Private mouseLocation As Point    ' <-- to be replaced
[COLOR=black]
Private mouseLocationX As Integer   ' <-- new line
Private mouseLocationY As Integer   ' <-- new line
[/color]
[/b]

' Changes in Label_GenericMouseDown Event.
' If e.Button = Windows.Forms.MouseButtons.Left Then
'    dragNow = True
[b]
'    mouseLocation = e.Location     ' <-- to be replaced
[COLOR=black]
     mouseLocationX = e.X           ' <-- new line
     mouseLocationY = e.Y           ' <-- new line
[/color]
[/b]
' End If

' Changes in Label_GenericMouseMove Event.
' If (dragNow = True) Then
[b]
'    CType(sender, Label).Location -= mouseLocation - e.Location   ' <-- to be replaced
[COLOR=black]
     CType(sender, Label).Left -= mouseLocationX - e.X   ' <-- new line
     CType(sender, Label).Top -= mouseLocationY - e.Y    ' <-- new line
[/color]
[/b]
' End If
[/color]

I aplogize for any errors in this code, because I've written it using windows Notepad. Infact I'm out of station and the laptop I've is not get installed any development software.

Hope this will help you out.
 
Thanks for the reply, however it still doesn't work right.

I have however finally figured out why, just not completely sure how to fix it as of yet.

When you click the 40 x 40 label located at 320x60 on the screen it gets the co-ordinates of the 40x40 label.. so if you were in the middle it would be 20x20 not the screen co-ords which would be 340x80. I hope you understand what I mean there.

But either way it's sending it back as 20,20 so that's what is creating the terrible ghosting. The above code created 4 total boxes, and it would randomly choose which one to position when you let go.

I'm still working on it keep the tips coming!
 
The co-ordinates returned are based on a controls position within its parent. That is to say 0,0 is the top left NOT of the hosting form, but of the control's parent.

I don't have VB running on this machine, but from memory there are positional conversion methos such as PointToClient, PointToScreen etc. and also the opposite way round. However if you adjust your postioning based on the position of the control's parent you shouldn't need to use them.

If I get a chance later I will put together a demo for you - but that wont be until around 8 pm (its now 2:15 pm)

Hope this helps.

[vampire][bat]
 
ok, well I'll still be playing with until this is resolved so by all means if you don't mind posting me a demo it would be greatly appreciated
 
Hi,
I've set up a little sample project(VS2003 French), I've tested it, it works like charm. Create a new form called Form1, and replace the code with this:

Code:
Public Class Form1
    Inherits System.Windows.Forms.Form

#Region " Code généré par le Concepteur Windows Form "

    Public Sub New()
        MyBase.New()

        'Cet appel est requis par le Concepteur Windows Form.
        InitializeComponent()

        'Ajoutez une initialisation quelconque après l'appel InitializeComponent()

    End Sub

    'La méthode substituée Dispose du formulaire pour nettoyer la liste des composants.
    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        If disposing Then
            If Not (components Is Nothing) Then
                components.Dispose()
            End If
        End If
        MyBase.Dispose(disposing)
    End Sub

    'Requis par le Concepteur Windows Form
    Private components As System.ComponentModel.IContainer

    'REMARQUE : la procédure suivante est requise par le Concepteur Windows Form
    'Elle peut être modifiée en utilisant le Concepteur Windows Form.  
    'Ne la modifiez pas en utilisant l'éditeur de code.
    Friend WithEvents btnAddLabels As System.Windows.Forms.Button
    Friend WithEvents Panel1 As System.Windows.Forms.Panel
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
        Me.btnAddLabels = New System.Windows.Forms.Button
        Me.Panel1 = New System.Windows.Forms.Panel
        Me.SuspendLayout()
        '
        'btnAddLabels
        '
        Me.btnAddLabels.Location = New System.Drawing.Point(12, 8)
        Me.btnAddLabels.Name = "btnAddLabels"
        Me.btnAddLabels.Size = New System.Drawing.Size(184, 23)
        Me.btnAddLabels.TabIndex = 0
        Me.btnAddLabels.Text = "Add 10 labels"
        '
        'Panel1
        '
        Me.Panel1.BackColor = System.Drawing.Color.Red
        Me.Panel1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle
        Me.Panel1.Location = New System.Drawing.Point(12, 40)
        Me.Panel1.Name = "Panel1"
        Me.Panel1.Size = New System.Drawing.Size(656, 416)
        Me.Panel1.TabIndex = 1
        '
        'Form1
        '
        Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
        Me.ClientSize = New System.Drawing.Size(680, 462)
        Me.Controls.Add(Me.Panel1)
        Me.Controls.Add(Me.btnAddLabels)
        Me.Name = "Form1"
        Me.Text = "Form1"
        Me.ResumeLayout(False)

    End Sub

#End Region

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

    End Sub

    Private Sub btnAddLabels_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAddLabels.Click

        Dim lblNew As Label

        For i As Integer = 0 To 10
            lblNew = New Label
            lblNew.Text = "Draggable Label"
            lblNew.BorderStyle = BorderStyle.FixedSingle
            lblNew.BackColor = Color.Yellow
            AddHandler lblNew.MouseDown, AddressOf DraggableLabel_MouseDown
            AddHandler lblNew.MouseMove, AddressOf DraggableLabel_MouseMove
            AddHandler lblNew.MouseUp, AddressOf DraggableLabel_MouseUp

            Me.Panel1.Controls.Add(lblNew)

        Next

    End Sub

    Dim m_cursor As Cursor
    Dim m_mouseX, m_mouseY As Integer

    Private Sub DraggableLabel_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)

        If e.Button = MouseButtons.Left Then

            Dim lblSender As Label = DirectCast(sender, Label)

            m_cursor = lblSender.Cursor
            lblSender.Cursor = Cursors.SizeAll
            m_mouseX = e.X
            m_mouseY = e.Y

        End If

    End Sub

    Private Sub DraggableLabel_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)

        If e.Button = MouseButtons.Left Then

            Dim lblSender As Label = DirectCast(sender, Label)

            lblSender.Location = New Point(lblSender.Location.X + (e.X-m_mouseX), _
                                           lblSender.Location.y + (e.y-m_mousey)) 
           
        End If

    End Sub

    Private Sub DraggableLabel_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)
      DirectCast(sender, Label).Cursor = m_cursor
    End Sub
End Class

Please let me know if it suits your requirements, if it does, I'll clean it, comment it and make a FAQ out of it.


---
If gray hair is a sign of wisdom, then talk like a pirate ninja monkey if you get the time to get funky once a week.
Wo bu zhi dao !
 
I see Mastakilla, beat me to it. Not to worry, my approach was slightly different:

Code:
Public Class Form1
    Inherits System.Windows.Forms.Form

#Region " Windows Form Designer generated code "

    Public Sub New()
        MyBase.New()

        'This call is required by the Windows Form Designer.
        InitializeComponent()

        'Add any initialization after the InitializeComponent() call

    End Sub

    'Form overrides dispose to clean up the component list.
    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        If disposing Then
            If Not (components Is Nothing) Then
                components.Dispose()
            End If
        End If
        MyBase.Dispose(disposing)
    End Sub

    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.  
    'Do not modify it using the code editor.
  Friend WithEvents Panel1 As System.Windows.Forms.Panel
  Friend WithEvents Panel2 As System.Windows.Forms.Panel
  Friend WithEvents Label1 As System.Windows.Forms.Label
  Friend WithEvents Label2 As System.Windows.Forms.Label
  Friend WithEvents Label3 As System.Windows.Forms.Label
  Friend WithEvents CheckBox1 As System.Windows.Forms.CheckBox
  <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
    Me.Panel1 = New System.Windows.Forms.Panel
    Me.Label1 = New System.Windows.Forms.Label
    Me.Panel2 = New System.Windows.Forms.Panel
    Me.Label2 = New System.Windows.Forms.Label
    Me.Label3 = New System.Windows.Forms.Label
    Me.CheckBox1 = New System.Windows.Forms.CheckBox
    Me.Panel1.SuspendLayout()
    Me.Panel2.SuspendLayout()
    Me.SuspendLayout()
    '
    'Panel1
    '
    Me.Panel1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle
    Me.Panel1.Controls.Add(Me.Label1)
    Me.Panel1.Location = New System.Drawing.Point(48, 120)
    Me.Panel1.Name = "Panel1"
    Me.Panel1.TabIndex = 0
    '
    'Label1
    '
    Me.Label1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle
    Me.Label1.Location = New System.Drawing.Point(24, 24)
    Me.Label1.Name = "Label1"
    Me.Label1.TabIndex = 0
    Me.Label1.Text = "Label1"
    '
    'Panel2
    '
    Me.Panel2.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle
    Me.Panel2.Controls.Add(Me.Label2)
    Me.Panel2.Location = New System.Drawing.Point(376, 128)
    Me.Panel2.Name = "Panel2"
    Me.Panel2.TabIndex = 1
    '
    'Label2
    '
    Me.Label2.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle
    Me.Label2.Location = New System.Drawing.Point(48, 24)
    Me.Label2.Name = "Label2"
    Me.Label2.TabIndex = 0
    Me.Label2.Text = "Label2"
    '
    'Label3
    '
    Me.Label3.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle
    Me.Label3.Location = New System.Drawing.Point(184, 32)
    Me.Label3.Name = "Label3"
    Me.Label3.TabIndex = 2
    Me.Label3.Text = "Label3"
    '
    'CheckBox1
    '
    Me.CheckBox1.Location = New System.Drawing.Point(40, 296)
    Me.CheckBox1.Name = "CheckBox1"
    Me.CheckBox1.TabIndex = 4
    Me.CheckBox1.Text = "Release Label2"
    '
    'Form1
    '
    Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
    Me.ClientSize = New System.Drawing.Size(712, 468)
    Me.Controls.Add(Me.CheckBox1)
    Me.Controls.Add(Me.Label3)
    Me.Controls.Add(Me.Panel2)
    Me.Controls.Add(Me.Panel1)
    Me.Name = "Form1"
    Me.Text = "Form1"
    Me.Panel1.ResumeLayout(False)
    Me.Panel2.ResumeLayout(False)
    Me.ResumeLayout(False)

  End Sub

#End Region

  Private LabelBeingMoved As Label = Nothing
  Private LabelMoving As Boolean = False
  Private LabelLocation As Point
  Private StartX As Integer
  Private StartY As Integer

  Private Sub Label_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles _
    Label1.MouseDown, Label2.MouseDown, Label3.MouseDown

    LabelBeingMoved = CType(sender, Label)
    LabelLocation = New Point(LabelBeingMoved.Left, LabelBeingMoved.Top)
    StartX = e.X
    StartY = e.Y
    LabelMoving = True

  End Sub

  Private Sub Label_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles _
    Label1.MouseMove, Label2.MouseMove, Label3.MouseMove

    If LabelMoving Then
      With LabelLocation
        .X = .X + (e.X - StartX)
        .Y = .Y + (e.Y - StartY)
      End With
      LabelBeingMoved.Location = LabelLocation
    End If

  End Sub

  Private Sub Label_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles _
    Label1.MouseUp, Label2.MouseUp, Label3.MouseUp

    LabelMoving = False

  End Sub

  'Little demo to show how to allow a Label to be moved into and out of its parent
  Private Sub CheckBox1_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CheckBox1.CheckedChanged

    If CheckBox1.Checked Then
      Label2.Parent = Me
      Label2.BringToFront()
      Label2.Location = _
        New Point(Panel2.Location.X + Label2.Location.X, Panel2.Location.Y + Label2.Location.Y)
    Else
      Label2.Parent = Panel2
      Label2.Location = _
        New Point(Label2.Location.X - Panel2.Location.X, Label2.Location.Y - Panel2.Location.Y)
      'make sure Label is inside the Panel
      If Label2.Bottom < 0 Or Label2.Top > Panel2.Height _
          Or Label2.Right < 0 Or Label2.Left > Panel2.Width Then
        Label2.Left = 0
        Label2.Top = 0
      End If
    End If

  End Sub
End Class


Hope this helps.

[vampire][bat]
 
I'd forgotten that you wanted to add the labels at run time - so a slight variation:

Code:
Public Class Form1
    Inherits System.Windows.Forms.Form

#Region " Windows Form Designer generated code "

    Public Sub New()
        MyBase.New()

        'This call is required by the Windows Form Designer.
        InitializeComponent()

        'Add any initialization after the InitializeComponent() call

    End Sub

    'Form overrides dispose to clean up the component list.
    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        If disposing Then
            If Not (components Is Nothing) Then
                components.Dispose()
            End If
        End If
        MyBase.Dispose(disposing)
    End Sub

    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.  
    'Do not modify it using the code editor.
  Friend WithEvents Panel1 As System.Windows.Forms.Panel
  Friend WithEvents Panel2 As System.Windows.Forms.Panel
  Friend WithEvents CheckBox1 As System.Windows.Forms.CheckBox
  Friend WithEvents Button1 As System.Windows.Forms.Button
  <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
    Me.Panel1 = New System.Windows.Forms.Panel
    Me.Panel2 = New System.Windows.Forms.Panel
    Me.CheckBox1 = New System.Windows.Forms.CheckBox
    Me.Button1 = New System.Windows.Forms.Button
    Me.SuspendLayout()
    '
    'Panel1
    '
    Me.Panel1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle
    Me.Panel1.Location = New System.Drawing.Point(48, 120)
    Me.Panel1.Name = "Panel1"
    Me.Panel1.TabIndex = 0
    '
    'Panel2
    '
    Me.Panel2.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle
    Me.Panel2.Location = New System.Drawing.Point(376, 128)
    Me.Panel2.Name = "Panel2"
    Me.Panel2.TabIndex = 1
    '
    'CheckBox1
    '
    Me.CheckBox1.Location = New System.Drawing.Point(40, 296)
    Me.CheckBox1.Name = "CheckBox1"
    Me.CheckBox1.TabIndex = 4
    Me.CheckBox1.Text = "Release Label2"
    '
    'Button1
    '
    Me.Button1.Location = New System.Drawing.Point(40, 336)
    Me.Button1.Name = "Button1"
    Me.Button1.TabIndex = 5
    Me.Button1.Text = "Button1"
    '
    'Form1
    '
    Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
    Me.ClientSize = New System.Drawing.Size(712, 468)
    Me.Controls.Add(Me.Button1)
    Me.Controls.Add(Me.CheckBox1)
    Me.Controls.Add(Me.Panel2)
    Me.Controls.Add(Me.Panel1)
    Me.Name = "Form1"
    Me.Text = "Form1"
    Me.ResumeLayout(False)

  End Sub

#End Region

  Private LabelBeingMoved As Label = Nothing
  Private LabelMoving As Boolean = False
  Private LabelLocation As Point
  Private StartX As Integer
  Private StartY As Integer
  Private ReleasableLabel As Label = Nothing

  Private Sub Label_MouseDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs)

    LabelBeingMoved = CType(sender, Label)
    LabelLocation = New Point(LabelBeingMoved.Left, LabelBeingMoved.Top)
    StartX = e.X
    StartY = e.Y
    LabelMoving = True

  End Sub

  Private Sub Label_MouseMove(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs)

    If LabelMoving Then
      With LabelLocation
        .X = .X + (e.X - StartX)
        .Y = .Y + (e.Y - StartY)
      End With
      LabelBeingMoved.Location = LabelLocation
    End If

  End Sub

  Private Sub Label_MouseUp(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs)

    LabelMoving = False

  End Sub

  'Little demo to show how to allow a Label to be moved into and out of its parent
  Private Sub CheckBox1_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CheckBox1.CheckedChanged

    With ReleasableLabel
      If CheckBox1.Checked Then
        .Parent = Me
        .BringToFront()
        .Location = _
          New Point(Panel2.Location.X + .Location.X, Panel2.Location.Y + .Location.Y)
      Else
        .Parent = Panel2
        .Location = _
          New Point(.Location.X - Panel2.Location.X, .Location.Y - Panel2.Location.Y)
        'make sure Label is inside the Panel
        If .Bottom < 0 Or .Top > Panel2.Height _
            Or .Right < 0 Or .Left > Panel2.Width Then
          .Left = 0
          .Top = 0
        End If
      End If
    End With

  End Sub

  Private Sub AddLabel(ByVal TheName As String, ByVal TheParent As Control, ByVal TheLocation As Point)

    Dim lbl As New Label
    With lbl
      .Name = TheName
      .Text = TheName
      .Location = TheLocation
      .BorderStyle = BorderStyle.FixedSingle
      .BackColor = Color.LightBlue
    End With
    TheParent.Controls.Add(lbl)
    AddHandler lbl.MouseDown, AddressOf Label_MouseDown
    AddHandler lbl.MouseMove, AddressOf Label_MouseMove
    AddHandler lbl.MouseUp, AddressOf Label_MouseUp
    If TheName = "Label2" Then ReleasableLabel = lbl

  End Sub

  Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

    AddLabel("Label1", Panel1, New Point(10, 10))
    AddLabel("Label2", Panel2, New Point(20, 20))
    AddLabel("Label3", Me, New Point(30, 30))

  End Sub
End Class


Hope this helps.

[vampire][bat]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top