Udostępnij za pośrednictwem


Connecting Label Controls

Question – I am starting to do some graphics work for a program that I am developing. I understand that the shape control has been removed from .NET and that I should be using GDI+. Personally, this seems to be a bit complicated and I can’t seem to figure it out. What I really need to do, is connect a variety of controls together with a line. Which should be pretty straight forward and for the life of me I can’t figure out how to do it - any ideas?

Answer – you are right in that the Shape control in Visual basic 6.0 has no equivalent in Visual Basic.Net. The .NET Framework, specifically the Common Language Runtime takes advantage of an advanced version of the Windows Graphics Device Interface (GDI) called GDI+. It supports 2-D graphics, typography, and imaging. The System.Drawing namespace provides access to the GDI+ basic graphic functionality.

The Gaphics object is used to encapsulate a GDI+ drawing surface. Once created it can be used to draw lines, shapes, render text or display and manipulate images. The principal objects that are used with the Graphics objects are:

  • Pen Class – Used to draw lines, outline shapes or rendering other representations
  • Brush Class – Used for filling graphics.
  • Font Class – Provide a description of what shapes to use when rendering text.
  • Color Structure – Represents the different colors to display.

Use the following steps to connect two label controls with a line

  1. Start a new Windows Form Project and drop 2 label controls and a button on the form as shown below.

  1. Double click and place the following code in the Button_Click event.

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

‘ create the pen object
Dim pen As New Drawing.Pen(System.Drawing.Color.Red, 1)

‘ define the points = X/Y for each
Dim point1 As New Point(Label1.Location.X, Label1.Location.Y)
Dim point2 As New Point(Label2.Location.X, Label2.Location.Y)

‘ draw it
Me.CreateGraphics.DrawLine(pen, point1, point2)

‘ always good practice
pen.Dispose()

End Sub

  1. Compile and start the application. Once started select the button. This will activate the code and draw the lines that connect the two label controls as shown below

Of course, this barely scratched the surface with the possibilities that you can do with GDI+.

Comments

  • Anonymous
    February 06, 2005
    The comment has been removed