Comment : développer un contrôle Windows Forms simple

Mise à jour : novembre 2007

Cette section décrit les étapes essentielles de la création d'un contrôle Windows Forms personnalisé. Le contrôle simple développé à l'aide de cette procédure permet de modifier l'alignement de sa propriété Text. Il ne déclenche ou ne gère aucun événement.

Pour créer un contrôle personnalisé simple

  1. Définissez une classe qui dérive de System.Windows.Forms.Control.

    Public Class FirstControl
       Inherits Control
    
    End Class
    
    public class FirstControl:Control{}
    
  2. Définissez les propriétés. (Vous n'êtes pas obligé de définir les propriétés, car un contrôle hérite de nombreuses propriétés de la classe Control, mais la plupart des contrôles personnalisés définissent généralement des propriétés supplémentaires.) Le fragment de code suivant définit une propriété appelée TextAlignment qui utilise FirstControl pour mettre en forme l'affichage de la propriété Text héritée de Control. Pour plus d'informations sur la définition des propriétés, consultez Vue d'ensemble des propriétés.

    ' ContentAlignment is an enumeration defined in the System.Drawing
    ' namespace that specifies the alignment of content on a drawing 
    ' surface.
    Private alignmentValue As ContentAlignment = ContentAlignment.MiddleLeft
    
    <Category("Alignment"), Description("Specifies the alignment of text.")> _
    Public Property TextAlignment() As ContentAlignment
    
       Get
          Return alignmentValue
       End Get
       Set
          alignmentValue = value
    
          ' The Invalidate method invokes the OnPaint method described 
          ' in step 3.
          Invalidate()
       End Set
    End Property
    
    // ContentAlignment is an enumeration defined in the System.Drawing
    // namespace that specifies the alignment of content on a drawing 
    // surface.
    private ContentAlignment alignmentValue = ContentAlignment.MiddleLeft;
    

    Lorsque vous définissez une propriété qui modifie l'affichage visuel du contrôle, vous devez appeler la méthode Invalidate pour redessiner le contrôle. Invalidate est défini dans la classe de base Control.

  3. Substituez la méthode OnPaint protégée héritée de Control afin de fournir une logique de rendu à votre contrôle. Si vous ne substituez pas OnPaint, votre contrôle est incapable de se dessiner. Dans le fragment de code suivant, la méthode OnPaint affiche la propriété Text héritée de Control avec l'alignement spécifié par le champ alignmentValue.

    Protected Overrides Sub OnPaint(e As PaintEventArgs)
    
       MyBase.OnPaint(e)
       Dim style As New StringFormat()
       style.Alignment = StringAlignment.Near
       Select Case alignmentValue
          Case ContentAlignment.MiddleLeft
             style.Alignment = StringAlignment.Near
          Case ContentAlignment.MiddleRight
             style.Alignment = StringAlignment.Far
          Case ContentAlignment.MiddleCenter
             style.Alignment = StringAlignment.Center
       End Select
    
       ' Call the DrawString method of the System.Drawing class to write   
       ' text. Text and ClientRectangle are properties inherited from
       ' Control.
       e.Graphics.DrawString( _
           me.Text, _
           me.Font, _
           New SolidBrush(ForeColor), _
           RectangleF.op_Implicit(ClientRectangle), _
           style)
    
    End Sub
    
    protected override void OnPaint(PaintEventArgs e) 
    {   
        base.OnPaint(e);
        StringFormat style = new StringFormat();
        style.Alignment = StringAlignment.Near;
        switch (alignmentValue) 
        {
            case ContentAlignment.MiddleLeft:
                style.Alignment = StringAlignment.Near;
                break;
            case ContentAlignment.MiddleRight:
                style.Alignment = StringAlignment.Far;
                break;
            case ContentAlignment.MiddleCenter:
                style.Alignment = StringAlignment.Center;
                break;
        }
    
        // Call the DrawString method of the System.Drawing class to write   
        // text. Text and ClientRectangle are properties inherited from
        // Control.
        e.Graphics.DrawString(
            Text, 
            Font, 
            new SolidBrush(ForeColor), 
            ClientRectangle, style);
    
    } 
    
  4. Fournissez des attributs pour votre contrôle. Les attributs permettent à un concepteur visuel d'afficher correctement votre contrôle ainsi que ses propriétés et événements au moment du design. Le fragment de code suivant applique des attributs à la propriété TextAlignment. Dans un concepteur tel que Visual Studio .NET, l'attribut Category (repris dans le fragment de code) entraîne l'affichage de la propriété sous une catégorie logique. L'attribut Description entraîne l'affichage d'une chaîne descriptive en bas de la fenêtre Propriétés lorsque la propriété TextAlignment est sélectionnée. Pour plus d'informations sur les attributs, consultez Attributs en mode design pour les composants.

    <Category("Alignment"), Description("Specifies the alignment of text.")> _
    Public Property TextAlignment() As ContentAlignment
    
    [
    Category("Alignment"),
    Description("Specifies the alignment of text.")
    ]
    
  5. (facultatif) Fournissez des ressources pour votre contrôle. Vous pouvez fournir une ressource, telle qu'une bitmap, pour votre contrôle en utilisant une option de compilateur (/respour C#) pour empaqueter des ressources avec votre contrôle. Au moment de l'exécution, la ressource peut être récupérée à l'aide des méthodes de la classe ResourceManager. Pour plus d'informations sur la création et l'utilisation des ressources, consultez Ressources dans les applications.

  6. Compilez et déployez votre contrôle. Pour compiler et déployer FirstControl, exécutez les étapes suivantes :

    1. Enregistrez le code de l'exemple suivant dans un fichier source (tel que FirstControl.cs ou FirstControl.vb).

    2. Compilez le code source dans un assembly et enregistrez-le dans le répertoire de votre application. Dans ce but, exécutez la commande suivante à partir du répertoire qui contient le fichier source.

      vbc /t:library /out:[path to your application's directory]/CustomWinControls.dll /r:System.dll /r:System.Windows.Forms.dll /r:System.Drawing.dll FirstControl.vb
      
      csc /t:library /out:[path to your application's directory]/CustomWinControls.dll /r:System.dll /r:System.Windows.Forms.dll /r:System.Drawing.dll FirstControl.cs
      

      L'option de compilateur /t:library indique au compilateur que l'assembly que vous créez est une bibliothèque (et non un exécutable). L'option /out spécifie le chemin d'accès et le nom de l'assembly. L'option /r fournit le nom des assemblys référencés par votre code. Dans cet exemple, vous créez un assembly privé que seules vos applications peuvent utiliser. Vous devez donc l'enregistrer dans le répertoire de votre application. Pour plus d'informations sur l'empaquetage et le déploiement d'un contrôle pour la distribution, consultez Déploiement d'applications .NET Framework.

L'exemple suivant montre le code pour FirstControl. Le contrôle est inséré dans l'espace de noms CustomWinControls. Un espace de noms fournit un regroupement logique des types connexes. Vous pouvez créer votre contrôle dans un nouvel espace de noms ou dans un espace de noms existant. En C#, la déclaration using (Imports en Visual Basic) permet d'accéder aux types à partir d'un espace de noms sans utiliser le nom qualifié complet du type. Dans l'exemple suivant, la déclaration using permet au code d'accéder à la classe Control à partir de System.Windows.Forms simplement en tant que Control au lieu de devoir utiliser le nom qualifié complet System.Windows.Forms.Control.

Imports System
Imports System.Drawing
Imports System.Collections
Imports System.ComponentModel
Imports System.Windows.Forms


Public Class FirstControl
   Inherits Control

   Public Sub New()
   End Sub 


   ' ContentAlignment is an enumeration defined in the System.Drawing
   ' namespace that specifies the alignment of content on a drawing 
   ' surface.
   Private alignmentValue As ContentAlignment = ContentAlignment.MiddleLeft

   <Category("Alignment"), Description("Specifies the alignment of text.")> _
   Public Property TextAlignment() As ContentAlignment

      Get
         Return alignmentValue
      End Get
      Set
         alignmentValue = value

         ' The Invalidate method invokes the OnPaint method described 
         ' in step 3.
         Invalidate()
      End Set
   End Property


   Protected Overrides Sub OnPaint(e As PaintEventArgs)

      MyBase.OnPaint(e)
      Dim style As New StringFormat()
      style.Alignment = StringAlignment.Near
      Select Case alignmentValue
         Case ContentAlignment.MiddleLeft
            style.Alignment = StringAlignment.Near
         Case ContentAlignment.MiddleRight
            style.Alignment = StringAlignment.Far
         Case ContentAlignment.MiddleCenter
            style.Alignment = StringAlignment.Center
      End Select

      ' Call the DrawString method of the System.Drawing class to write   
      ' text. Text and ClientRectangle are properties inherited from
      ' Control.
      e.Graphics.DrawString( _
          me.Text, _
          me.Font, _
          New SolidBrush(ForeColor), _
          RectangleF.op_Implicit(ClientRectangle), _
          style)

   End Sub

End Class
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;

namespace CustomWinControls
{
    public class FirstControl : Control
    {

        public FirstControl()
        {

        }

        // ContentAlignment is an enumeration defined in the System.Drawing
        // namespace that specifies the alignment of content on a drawing 
        // surface.
        private ContentAlignment alignmentValue = ContentAlignment.MiddleLeft;

        [
        Category("Alignment"),
        Description("Specifies the alignment of text.")
        ]
        public ContentAlignment TextAlignment 
        {

            get 
            {
                return alignmentValue;
            }
            set 
            {
                alignmentValue = value;

                // The Invalidate method invokes the OnPaint method described 
                // in step 3.
                Invalidate(); 
            }
        }


        protected override void OnPaint(PaintEventArgs e) 
        {   
            base.OnPaint(e);
            StringFormat style = new StringFormat();
            style.Alignment = StringAlignment.Near;
            switch (alignmentValue) 
            {
                case ContentAlignment.MiddleLeft:
                    style.Alignment = StringAlignment.Near;
                    break;
                case ContentAlignment.MiddleRight:
                    style.Alignment = StringAlignment.Far;
                    break;
                case ContentAlignment.MiddleCenter:
                    style.Alignment = StringAlignment.Center;
                    break;
            }

            // Call the DrawString method of the System.Drawing class to write   
            // text. Text and ClientRectangle are properties inherited from
            // Control.
            e.Graphics.DrawString(
                Text, 
                Font, 
                new SolidBrush(ForeColor), 
                ClientRectangle, style);

        } 
    }
}

Utilisation du contrôle personnalisé dans un formulaire

L'exemple suivant montre un formulaire simple qui utilise FirstControl. Il crée trois instances de FirstControl, chacune possédant une valeur différente pour la propriété TextAlignment.

Pour compiler et exécuter cet exemple

  1. Enregistrez le code de l'exemple suivant dans un fichier source (SimpleForm.cs ou SimpleForms.vb).

  2. Compilez le code source dans un assembly exécutable en lançant la commande suivante à partir du répertoire qui contient le fichier source.

    vbc /r:CustomWinControls.dll /r:System.dll /r:System.Windows.Forms.dll /r:System.Drawing.dll SimpleForm.vb
    
    csc /r:CustomWinControls.dll /r:System.dll /r:System.Windows.Forms.dll /r:System.Drawing.dll SimpleForm.cs
    

    CustomWinControls.dll est l'assembly qui contient la classe FirstControl. Cet assembly doit se trouver dans le même répertoire que le fichier source du formulaire qui y accède (SimpleForm.cs ou SimpleForms.vb).

  3. Exécutez SimpleForm.exe à l'aide de la commande suivante.

    SimpleForm
    
Imports System
Imports System.Drawing
Imports System.Collections
Imports System.ComponentModel
Imports System.Windows.Forms




Public Class SimpleForm
   Inherits System.Windows.Forms.Form

   Private firstControl1 As FirstControl

   Private components As System.ComponentModel.Container = Nothing


   Public Sub New()
      InitializeComponent()
   End Sub 





   Private Sub InitializeComponent()
      Me.firstControl1 = New FirstControl()
      Me.SuspendLayout()

      ' 
      ' firstControl1
      ' 
      Me.firstControl1.BackColor = System.Drawing.SystemColors.ControlDark
      Me.firstControl1.Location = New System.Drawing.Point(96, 104)
      Me.firstControl1.Name = "firstControl1"
      Me.firstControl1.Size = New System.Drawing.Size(75, 16)
      Me.firstControl1.TabIndex = 0
      Me.firstControl1.Text = "Hello World"
      Me.firstControl1.TextAlignment = System.Drawing.ContentAlignment.MiddleCenter

      ' 
      ' SimpleForm
      ' 
      Me.ClientSize = New System.Drawing.Size(292, 266)
      Me.Controls.Add(firstControl1)
      Me.Name = "SimpleForm"
      Me.Text = "SimpleForm"
      Me.ResumeLayout(False)
   End Sub 


   <STAThread()>  _
   Shared Sub Main()
      Application.Run(New SimpleForm())
   End Sub 
End Class 
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;

namespace CustomWinControls
{

    public class SimpleForm : System.Windows.Forms.Form
    {
        private FirstControl firstControl1;

        private System.ComponentModel.Container components = null;

        public SimpleForm()
        {
            InitializeComponent();
        }

        protected override void Dispose( bool disposing )
        {
            if( disposing )
            {
                if (components != null) 
                {
                    components.Dispose();
                }
            }
            base.Dispose( disposing );
        }

        private void InitializeComponent()
        {
            this.firstControl1 = new FirstControl();
            this.SuspendLayout();

            // 
            // firstControl1
            // 
            this.firstControl1.BackColor = System.Drawing.SystemColors.ControlDark;
            this.firstControl1.Location = new System.Drawing.Point(96, 104);
            this.firstControl1.Name = "firstControl1";
            this.firstControl1.Size = new System.Drawing.Size(75, 16);
            this.firstControl1.TabIndex = 0;
            this.firstControl1.Text = "Hello World";
            this.firstControl1.TextAlignment = System.Drawing.ContentAlignment.MiddleCenter;

            // 
            // SimpleForm
            // 
            this.ClientSize = new System.Drawing.Size(292, 266);
            this.Controls.Add(this.firstControl1);
            this.Name = "SimpleForm";
            this.Text = "SimpleForm";
            this.ResumeLayout(false);

        }

        [STAThread]
        static void Main() 
        {
            Application.Run(new SimpleForm());
        }


    }
}

Voir aussi

Concepts

Événements dans les contrôles Windows Forms

Autres ressources

Propriétés dans les contrôles Windows Forms