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
-
Définissez une classe qui dérive de System.Windows.Forms.Control.
Visual BasicPublic Class FirstControl Inherits Control End Class
C#public class FirstControl:Control{}
-
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.
Visual Basic' 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
C#// 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.
-
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.
Visual BasicProtected 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
C#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); }
-
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.
Visual Basic<Category("Alignment"), Description("Specifies the alignment of text.")> _ Public Property TextAlignment() As ContentAlignment
C#[ Category("Alignment"), Description("Specifies the alignment of text.") ] -
(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.
-
Compilez et déployez votre contrôle. Pour compiler et déployer FirstControl, exécutez les étapes suivantes :
-
Enregistrez le code de l'exemple suivant dans un fichier source (tel que FirstControl.cs ou FirstControl.vb).
-
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.
Visual Basicvbc /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
C#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
-
Enregistrez le code de l'exemple suivant dans un fichier source (SimpleForm.cs ou SimpleForms.vb).
-
Compilez le code source dans un assembly exécutable en lançant la commande suivante à partir du répertoire qui contient le fichier source.
Visual Basicvbc /r:CustomWinControls.dll /r:System.dll /r:System.Windows.Forms.dll /r:System.Drawing.dll SimpleForm.vb
C#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).
-
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 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); } } }
Outils (masquer)
S'enregistrer
Liste des Membres
Qui est en ligne?
FAQ