Numéro d'article: 309480 - Dernière mise à jour: vendredi 11 mai 2007 - Version: 2.5

Comment créer des fonctionnalités similaires aux contrôles ligne et la forme dans Windows Forms à l'aide de Visual Basic .NET ou Visual Basic 2005

Sommaire

Agrandir tout | Réduire tout

Résumé

Cet article explique comment dessiner traits et des formes dans Microsoft Visual Basic .NET ou dans Microsoft Visual Basic 2005 en utilisant le code exemple inclus. La fonctionnalité qui est démontrée est similaire à celui qui est fournie par les contrôles ligne et la forme sont disponibles dans Microsoft Visual Basic 6.0. Les contrôles de ligne et la forme ne sont pas inclus dans Visual Basic .NET ou dans Visual Basic 2005 ; toutefois, l'espace de noms System.Drawing est disponible et cet espace de noms permet fonctionnalités, polyvalence et contrôler lignes et des formes.

Créez le projet et ajouter le code

  1. Démarrez Visual Studio .NET ou Visual Studio 2005.
  2. Créez une nouvelle application Windows dans Visual Basic .NET ou Visual Basic 2005.
  3. Ajoutez quatre boutons et une étiquette à Form1 (l'emplacement des boutons et l'étiquette n'est pas important).
  4. Double-cliquez sur Form1 pour ouvrir la fenêtre de code.
  5. Utilisez l'instruction IMPORTS sur les espaces de noms afin que vous n'êtes pas nécessaire de qualifier les déclarations dans les espaces de noms plus loin dans votre code.

    Ajoutez le code suivant à la section Déclarations générales de Form1 (qui est la section ci-dessus tout autre code dans la fenêtre):
    Imports System.ComponentModel
    Imports System.Drawing
    					
  6. Collez le code suivant après le code généré par le concepteur de formulaires Windows : Remarque : Veuillez visualiser les commentaires dans le code d'une brève explication de la fonctionnalité.
        'Declare the point variable to use in the Form1 Mouseup event.
        Dim p As Point
        Dim p2 As Point
        
        Private Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
            'Call the Sub to draw lines.
            DrawLines()
        End Sub
        Public Sub DrawLines()
            'Create a graphics object.
            Dim myGraphics As System.Drawing.Graphics
    
            'Set the graphics object of Form1 to the graphics object created to use Form1 to do our drawing.
            myGraphics = Me.CreateGraphics
    
            'Create the Pen object. A Pen object draws a line of specified width and style. 
            'The line drawn by a Pen object can be filled in a variety of fill styles, 
            'including solid colors and textures. The fill style depends on the brush or texture 
            'that is used as the fill object.
            Dim BluePen As New Pen(Color.Blue, 5)
    
            'Specify a cap style that the Pen object will use at the end of a line.
            BluePen.StartCap = Drawing.Drawing2D.LineCap.ArrowAnchor
    
            'This code block demonstrates how to draw straight lines of different varieties.
            'Use the DashStyle property of the Pen object to draw several varieties of dashed lines. 
            Dim x1, y1, x2, y2 As Single
            x1 = 166.0F
            x2 = 424.0F
            BluePen.DashStyle = Drawing.Drawing2D.DashStyle.Solid 'This draws a line to the screen. 
            myGraphics.DrawLine(BluePen, x1, 170, x2, 170)
            BluePen.DashStyle = Drawing.Drawing2D.DashStyle.Dash 'This draws a Dash line to the screen.
            myGraphics.DrawLine(BluePen, x1, 190, x2, 190)
            BluePen.DashStyle = Drawing.Drawing2D.DashStyle.DashDot 'This draws a Dash Dot line to the screen.
            myGraphics.DrawLine(BluePen, x1, 210, x2, 210)
            BluePen.DashStyle = Drawing.Drawing2D.DashStyle.DashDotDot 'This draws a Dash Dot Dot line to the screen.
            myGraphics.DrawLine(BluePen, x1, 230, x2, 230)
            BluePen.DashStyle = Drawing.Drawing2D.DashStyle.Dot 'This draws a Dotted line to the screen.
            myGraphics.DrawLine(BluePen, x1, 250, x2, 250)
    
        End Sub
    
        Private Sub Form1_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles MyBase.MouseUp
            'Generate a line on Form1 based on the user clicking two areas of Form1.
            If p.X <= 0 Then
                p.X = e.X 'This is the X coordinate of the mouse on Form1 and is set to the variable p that is type point.
                p.Y = e.Y 'This is the y coordinate of the mouse on Form1 and is set to the variable p that is type point.
            Else
                p2.X = e.X 'This is the X coordinate of the mouse on Form1 and is set to the variable p that is type point.
                p2.Y = e.Y 'This is the y coordinate of the mouse on Form1 and is set to the variable p that is type point.
    
                'Create a graphics object.
                Dim myGraphics As System.Drawing.Graphics
    
                'Set the graphics object of Form1 to the graphics object created to use Form1 to do our drawing.
                myGraphics = Me.CreateGraphics
    
                'Create the pen object. A Pen object draws a line of specified width and style. 
                'The line drawn by a Pen object can be filled in a variety of fill styles, 
                'including solid colors and textures. The fill style depends on the brush or texture 
                'that is used as the fill object.
                Dim BluePen As New Pen(Color.Blue, 5)
                'Draw the line.
                myGraphics.DrawLine(BluePen, p.X, p.Y, p2.X, p2.Y)
    
                p.X = 0
                p.Y = 0
            End If
    
        End Sub
        Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
            DrawShapes()
        End Sub
        Private Sub DrawShapes()
            'Create a graphics object.
            Dim myGraphics As System.Drawing.Graphics
    
            'Set the graphics object of Form1 to the graphics object created to use Form1 to do the drawing.
            myGraphics = Me.CreateGraphics
    
            'Create the pen object. A Pen object draws a line of specified width and style. 
            'The line drawn by a Pen object can be filled in a variety of fill styles, 
            'including solid colors and textures. The fill style depends on the brush or texture 
            'that is used as the fill object.
            Dim BluePen As New Pen(Color.Blue, 5)
    
            'The following code block draws shapes.
            myGraphics.DrawArc(BluePen, 200, 20, 100, 200, 45, 270)
            myGraphics.DrawBezier(BluePen, 100, 100, 200, 10, 350, 50, 500, 100)
            myGraphics.DrawRectangle(BluePen, 175, 200, 195, 200)
    
            'Create points that define the polygon.
            Dim myPointArray As Point() = _
                            {New Point(300, 123), New Point(472, 41), New Point(472, 156)}
            'Draw the polygon.
            myGraphics.DrawPolygon(BluePen, myPointArray)
    
            'Create a new Font object and set it equal to a FontStyle.
            Dim font As New Font("Times New Roman", 80, FontStyle.Regular, GraphicsUnit.Pixel, 1)
    
            'Create a new Brush object and set its value.
            Dim mybrush As Brush = Brushes.YellowGreen
    
            'Use the following code to draw text to the screen.
            myGraphics.DrawString(".NET", font, mybrush, 160, 200)
    
        End Sub
    
        Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
            Me.Refresh()'This clears the form
        End Sub
    
        Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            'This code formats the controls and Form1. 
            'Button1
            '
            Me.Button1.Location = New System.Drawing.Point(0, 0)
            Me.Button1.Name = "Button1"
            Me.Button1.Size = New System.Drawing.Size(88, 32)
            Me.Button1.TabIndex = 0
            Me.Button1.Text = "Draw Lines"
            '
            'Label1
            '
            Me.Label1.FlatStyle = System.Windows.Forms.FlatStyle.Flat
            Me.Label1.Location = New System.Drawing.Point(0, 112)
            Me.Label1.Name = "Label1"
            Me.Label1.Size = New System.Drawing.Size(120, 40)
            Me.Label1.TabIndex = 1
            Me.Label1.Text = "Click two places on the form to draw a line."
            '
            'Button2
            '
            Me.Button2.Location = New System.Drawing.Point(0, 32)
            Me.Button2.Name = "Button2"
            Me.Button2.Size = New System.Drawing.Size(88, 32)
            Me.Button2.TabIndex = 2
            Me.Button2.Text = "Draw Shapes"
            '
            'Button3
            '
            Me.Button3.Location = New System.Drawing.Point(120, 0)
            Me.Button3.Name = "Button3"
            Me.Button3.Size = New System.Drawing.Size(80, 32)
            Me.Button3.TabIndex = 3
            Me.Button3.Text = "Clear the Form"
            '
            'Button4
            '
            Me.Button4.Location = New System.Drawing.Point(0, 64)
            Me.Button4.Name = "Button4"
            Me.Button4.Size = New System.Drawing.Size(88, 32)
            Me.Button4.TabIndex = 4
            Me.Button4.Text = "Draw Filled Shapes"
            '
            'Form1
            '
            Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
            Me.ClientSize = New System.Drawing.Size(544, 406)
            Me.Controls.AddRange(New System.Windows.Forms.Control() {Me.Button4, Me.Button3, Me.Button2, Me.Label1, Me.Button1})
            Me.Name = "Form1"
            Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen
            Me.ResumeLayout(False)
        End Sub
    
        Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
            DrawFilledShapes()
    
        End Sub
        Private Sub DrawFilledShapes()
            'Create the pen object. A Pen object draws a line of specified width and style. 
            'The line drawn by a Pen object can be filled in a variety of fill styles, 
            'including solid colors and textures. The fill style depends on the brush or texture 
            'that is used as the fill object.
            Dim BluePen As New Pen(Color.Blue, 5)
    
            'Create a graphics object.
            Dim myGraphics As System.Drawing.Graphics
    
            'Set the graphics object of Form1 to the graphics object created to use Form1 to do the drawing.
            myGraphics = Me.CreateGraphics
    
            'The following code initializes a new SolidBrush object of the specified color.
            Dim solidBrush As New SolidBrush(Color.FromArgb(255, 255, 0, 0))
    
            'Fill an Ellipse area on the screen.
            myGraphics.FillEllipse(solidBrush, 70, 170, 100, 60)
    
            'Fill the rectangle that you created previously.
            myGraphics.FillRectangle(solidBrush, 175, 200, 195, 200)
        End Sub
    					
    Remarque vous devez modifier le code dans Visual Basic 2005. Par défaut, Visual Basic crée deux fichiers pour le projet lorsque vous créez un projet Windows Forms. Si le formulaire est nommé Form1, les fichiers deux qui représentent le formulaire sont nommés Form1.vb et Form1.Designer.vb. Vous écrivez le code dans le fichier Form1.vb. Le concepteur Windows Forms écrit le code dans le fichier Form1.Designer.vb. Le concepteur Windows Forms utilise le mot clé partiel pour répartir l'implémentation de Form1 en deux fichiers distincts. Ce comportement empêche le code concepteur généré d'être insérés dans votre code.

    Pour plus d'informations sur les nouvelles améliorations de langage Visual Basic 2005, reportez-vous au site de Web MSDN (Microsoft Developer Network) suivant :
    http://msdn2.microsoft.com/en-us/library/ms379584(vs.80).aspx (http://msdn2.microsoft.com/en-us/library/ms379584(vs.80).aspx)
    Pour plus d'informations sur des classes partielles et le concepteur Windows Forms, reportez-vous au site Web MSDN suivant :
    http://msdn2.microsoft.com/en-us/library/ms171843.aspx (http://msdn2.microsoft.com/en-us/library/ms171843.aspx)
  7. Enregistrez le projet.
  8. Dans le menu Déboguer , cliquez sur Démarrer , puis exécutez le projet.

Les informations contenues dans cet article s'appliquent au(x) produit(s) suivant(s):
  • Microsoft Visual Basic 2005
  • Microsoft Visual Basic .NET 2003 Initiation
  • Microsoft Visual Basic .NET 2002 Initiation
Mots-clés : 
kbmt kbvs2005applies kbvs2005swept kbhowtomaster KB309480 KbMtfr
Traduction automatiqueTraduction automatique
IMPORTANT : Cet article est issu du système de traduction automatique mis au point par Microsoft (http://support.microsoft.com/gp/mtdetails). Un certain nombre d?articles obtenus par traduction automatique sont en effet mis à votre disposition en complément des articles traduits en langue française par des traducteurs professionnels. Cela vous permet d?avoir accès, dans votre propre langue, à l?ensemble des articles de la base de connaissances rédigés originellement en langue anglaise. Les articles traduits automatiquement ne sont pas toujours parfaits et peuvent comporter des erreurs de vocabulaire, de syntaxe ou de grammaire (probablement semblables aux erreurs que ferait une personne étrangère s?exprimant dans votre langue !). Néanmoins, mis à part ces imperfections, ces articles devraient suffire à vous orienter et à vous aider à résoudre votre problème. Microsoft s?efforce aussi continuellement de faire évoluer son système de traduction automatique.
La version anglaise de cet article est la suivante: 309480  (http://support.microsoft.com/kb/309480/en-us/ )
L'INFORMATION CONTENUE DANS CE DOCUMENT EST FOURNIE PAR MICROSOFT SANS GARANTIE D'AUCUNE SORTE, EXPLICITE OU IMPLICITE. L'UTILISATEUR ASSUME LE RISQUE DE L'UTILISATION DU CONTENU DE CE DOCUMENT. CE DOCUMENT NE PEUT ETRE REVENDU OU CEDE EN ECHANGE D'UN QUELCONQUE PROFIT.
 

Traductions disponibles