Création d’un contrôle de boîte à outils Windows FormsCreating a Windows Forms Toolbox Control
Le modèle d’élément de contrôle de boîte à outils Windows Forms qui est inclus dans les outils d’extensibilité de Visual Studio (Visual Studio SDK) vous permet de créer un contrôle qui est automatiquement ajouté à la boîte à outils lorsque l’extension est installée.The Windows Forms Toolbox Control item template that is included in the Visual Studio Extensibility Tools (VS SDK) lets you create a control that is automatically added to the Toolbox when the extension is installed. Cette rubrique montre comment utiliser le modèle pour créer un contrôle de compteur simple que vous pouvez distribuer à d’autres utilisateurs.This topic shows how to use the template to create a simple counter control that you can distribute to other users.
PrérequisPrerequisites
À partir de Visual Studio 2015, vous n’installez pas le Kit de développement logiciel Visual Studio à partir du centre de téléchargement.Starting in Visual Studio 2015, you do not install the Visual Studio SDK from the download center. Il est inclus comme une fonctionnalité facultative dans le programme d’installation de Visual Studio.It is included as an optional feature in Visual Studio setup. Vous pouvez également installer le kit SDK VS ultérieurement.You can also install the VS SDK later on. Pour plus d’informations, consultez l’installation de Visual Studio SDK.For more information, see Installing the Visual Studio SDK.
Création d’un contrôle de boîte à outils Windows FormsCreating a Windows Forms Toolbox Control
Le modèle de contrôle de boîte à outils Windows Forms crée un contrôle utilisateur non défini et fournit toutes les fonctionnalités requises pour ajouter le contrôle à la boîte à outils.The Windows Forms Toolbox Control template creates an undefined user control and provides all of the functionality that is required to add the control to the Toolbox.
Créer une extension avec un contrôle de boîte à outils Windows FormsCreate an extension with a Windows Forms Toolbox Control
Créez un projet VSIX nommé
MyWinFormsControl
.Create a VSIX project namedMyWinFormsControl
. Vous pouvez trouver le modèle de projet VSIX dans le nouveau projet boîte de dialogue sous Visual c# / extensibilité.You can find the VSIX project template in the New Project dialog under Visual C# / Extensibility.Lorsque le projet s’ouvre, ajoutez un contrôle de boîte à outils Windows Forms modèle d’élément nommé
Counter
.When the project opens, add a Windows Forms Toolbox Control item template namedCounter
. Dans le l’Explorateur de solutions, cliquez sur le nœud du projet et sélectionnez Ajouter / nouvel élément.In the Solution Explorer, right-click the project node and select Add / New Item. Dans le ajouter un nouvel élément boîte de dialogue, accédez à Visual c# / extensibilité et sélectionnez contrôle de boîte à outils Windows FormsIn the Add New Item dialog, go to Visual C# / Extensibility and select Windows Forms Toolbox ControlCela ajoute un contrôle utilisateur, un
ProvideToolboxControlAttribute
RegistrationAttribute pour placer le contrôle dans le boîte à outilset un Microsoft.VisualStudio.ToolboxControl entrée de ressource dans le manifeste VSIX pour le déploiement.This adds a user control, aProvideToolboxControlAttribute
RegistrationAttribute to place the control in the Toolbox, and a Microsoft.VisualStudio.ToolboxControl Asset entry in the VSIX manifest for deployment.
Création d’une interface utilisateur pour le contrôleBuilding a User Interface for the Control
Le Counter
contrôle requiert deux contrôles enfants : un Label pour afficher le nombre actuel et un Button pour réinitialiser le nombre à 0.The Counter
control requires two child controls: a Label to display the current count, and a Button to reset the count to 0. Aucun autre contrôle enfant n’est requis, car les appelants incrémente le compteur par programmation.No other child controls are required because callers will increment the counter programmatically.
Pour créer l’interface utilisateurTo build the user interface
Dans l’Explorateur de solutions, double-cliquez sur Counter.cs pour l’ouvrir dans le concepteur.In Solution Explorer, double-click Counter.cs to open it in the designer.
Supprimer le « cliquez ici ! »Remove the "Click Here !" Bouton qui est inclus par défaut, lorsque vous ajoutez le modèle d’élément de contrôle de boîte à outils Windows Forms.Button that is included by default when you add the Windows Forms Toolbox Control item template.
À partir de la boîte à outils, faites glisser un
Label
contrôle, puis unButton
contrôle dessous à l’aire de conception.From the Toolbox, drag aLabel
control and then aButton
control below it to the design surface.Redimensionner le contrôle utilisateur globale de 150, 50 pixels et redimensionnez le bouton de contrôlent à 50, 20 pixels.Resize the overall user control to 150, 50 pixels, and resize the button control to 50, 20 pixels.
Dans le propriétés fenêtre, définissez les valeurs suivantes pour les contrôles sur l’aire de conception.In the Properties window, set the following values for the controls on the design surface.
ContrôleControl PropriétéProperty ValueValue Label1
TextText """" Button1
NameName btnResetbtnReset Button1
TextText RéinitialiserReset
Codage du contrôle utilisateurCoding the User Control
Le contrôle Counter
expose une méthode pour incrémenter le compteur, un événement à déclencher chaque fois que le compteur est incrémenté, un bouton Reset
et trois propriétés pour stocker le nombre actuel, stocker le texte affiché et indiquer s’il convient d’afficher ou de masquer le bouton Reset
.The Counter
control will expose a method to increment the counter, an event to be raised whenever the counter is incremented, a Reset
button, and three properties to store the current count, the display text, and whether to show or hide the Reset
button. Le ProvideToolboxControl
attribut détermine où, dans le boîte à outils le Counter
contrôle s’affiche.The ProvideToolboxControl
attribute determines where in the Toolbox the Counter
control will appear.
Pour coder le contrôle utilisateurTo code the user control
Double-cliquez sur le formulaire pour ouvrir son gestionnaire d’événements de charge dans la fenêtre de code.Double-click the form to open its load event handler in the code window.
Au-dessus de la méthode de gestionnaire d’événements, dans la classe du contrôle, créez un nombre entier pour stocker la valeur du compteur et une chaîne pour stocker le texte à afficher comme indiqué dans l’exemple suivant.Above the event handler method, in the control class create an integer to store the counter value and a string to store the display text as shown in the following example.
int currentValue; string displayText;
Créer les déclarations suivantes de la propriété publique.Create the following public property declarations.
public int Value { get { return currentValue; } } public string Message { get { return displayText; } set { displayText = value; } } public bool ShowReset { get { return btnReset.Visible; } set { btnReset.Visible = value; } }
Les appelants peuvent accéder à ces propriétés pour obtenir et définir le texte d’affichage du compteur et pour afficher ou masquer la
Reset
bouton.Callers can access these properties to get and set the display text of the counter and to show or hide theReset
button. Les appelants peuvent obtenir la valeur actuelle de la lecture seuleValue
propriété, mais ils ne peuvent pas définir la valeur directement.Callers can obtain the current value of the read-onlyValue
property, but they cannot set the value directly.Placez le code suivant le
Load
événement pour le contrôle.Put the following code in theLoad
event for the control.private void Counter_Load(object sender, EventArgs e) { currentValue = 0; label1.Text = Message + Value; }
Définition de la étiquette texte dans le Load événement Active les propriétés de la cible à charger avant que leurs valeurs sont appliquées.Setting the Label text in the Load event enables the target properties to load before their values are applied. Définition de la étiquette vide entraînera le texte dans le constructeur étiquette.Setting the Label text in the constructor would result in an empty Label.
Créez la méthode publique suivante pour incrémenter le compteur.Create the following public method to increment the counter.
public void Increment() { currentValue++; label1.Text = displayText + Value; Incremented(this, EventArgs.Empty); }
Ajoutez une déclaration pour le
Incremented
événement à la classe du contrôle.Add a declaration for theIncremented
event to the control class.public event EventHandler Incremented;
Les appelants peuvent ajouter des gestionnaires à cet événement pour répondre aux modifications de la valeur du compteur.Callers can add handlers to this event to respond to changes in the value of the counter.
Revenir au mode design et double-cliquez sur le
Reset
bouton pour générer lebtnReset_Click
Gestionnaire d’événements et le remplir dans comme illustré dans l’exemple suivant.Return to design view and double-click theReset
button to generate thebtnReset_Click
event handler, and then fill it in as shown in the following example.private void btnReset_Click(object sender, EventArgs e) { currentValue = 0; label1.Text = displayText + Value; }
Immédiatement au-dessus de la définition de classe, dans le
ProvideToolboxControl
déclaration d’attribut, modifiez la valeur du premier paramètre de"MyWinFormsControl.Counter"
à"General"
.Immediately above the class definition, in theProvideToolboxControl
attribute declaration, change the value of the first parameter from"MyWinFormsControl.Counter"
to"General"
. Le nom du groupe d’éléments qui va héberger le contrôle dans la boîte à outilsest ainsi défini.This sets the name of the item group that will host the control in the Toolbox.L’exemple suivant illustre l’attribut
ProvideToolboxControl
et la définition de classe ajustée.The following example shows theProvideToolboxControl
attribute and the adjusted class definition.[ProvideToolboxControl("General", false)] public partial class Counter : UserControl
Test du contrôleTesting the Control
Pour tester un boîte à outils contrôler, testez-le d’abord dans l’environnement de développement et à le tester dans une application compilée.To test a Toolbox control, first test it in the development environment and then test it in a compiled application.
Pour tester le contrôleTo test the control
Appuyez sur F5.Press F5.
Cela génère le projet et ouvre une seconde instance expérimentale de Visual Studio qui a le contrôle est installé.This builds the project and opens a second Experimental instance of Visual Studio that has the control installed.
Dans l’instance expérimentale de Visual Studio, créez un Application Windows Forms projet.In the Experimental instance of Visual Studio, create a Windows Forms Application project.
Dans l’Explorateur de solutions, double-cliquez sur Form1.cs pour l’ouvrir dans le concepteur s’il n’est pas déjà ouvert.In Solution Explorer, double-click Form1.cs to open it in the designer if it is not already open.
Dans le boîte à outils, le
Counter
contrôle doit être affiché dans le général section.In the Toolbox, theCounter
control should be displayed in the General section.Faites glisser un
Counter
le contrôle à votre formulaire, puis sélectionnez-le.Drag aCounter
control to your form, and then select it. LeValue
,Message
, etShowReset
propriétés sont affichées dans le propriétés fenêtre, ainsi que les propriétés sont héritées de UserControl.TheValue
,Message
, andShowReset
properties will be displayed in the Properties window, together with the properties that are inherited from UserControl.Affectez à la propriété
Message
la valeurCount:
.Set theMessage
property toCount:
.Faites glisser un Button au formulaire, puis définissez les propriétés de nom et le texte du bouton
Test
.Drag a Button control to the form, and then set the name and text properties of the button toTest
.Double-cliquez sur le bouton pour ouvrir Form1.cs en mode code et créer un gestionnaire.Double-click the button to open Form1.cs in code view and create a click handler.
Dans le gestionnaire click, appelez
counter1.Increment()
.In the click handler, callcounter1.Increment()
.Dans la fonction constructeur, après l’appel à
InitializeComponent
, typecounter1``.``Incremented +=
et appuyez sur TAB à deux reprises.In the constructor function, after the call toInitializeComponent
, typecounter1``.``Incremented +=
and then press TAB twice.Visual Studio génère un gestionnaire au niveau du formulaire pour le
counter1.Incremented
événement.Visual Studio generates a form-level handler for thecounter1.Incremented
event.Mettez en surbrillance le
Throw
instruction dans le Gestionnaire d’événements, typembox
, puis appuyez sur TAB à deux reprises pour générer une boîte de message à partir de l’extrait de code mbox.Highlight theThrow
statement in the event handler, typembox
, and then press TAB twice to generate a message box from the mbox code snippet.Sur la ligne suivante, ajoutez le code suivant
if
/else
bloc pour définir la visibilité de laReset
bouton.On the next line, add the followingif
/else
block to set the visibility of theReset
button.if (counter1.Value < 5) counter1.ShowReset = false; else counter1.ShowReset = true;
Appuyez sur F5.Press F5.
Le formulaire s’ouvre.The form opens. Le
Counter
contrôle affiche le texte suivant.TheCounter
control displays the following text.Nombre : 0Count: 0
Cliquez sur Test.Click Test.
Le compteur s’incrémente et Visual Studio affiche une boîte de message.The counter increments and Visual Studio displays a message box.
Fermez la boîte de message.Close the message box.
Le réinitialiser bouton disparaît.The Reset button disappears.
Cliquez sur Test jusqu'à ce que le compteur atteint 5 fermer le message boîtes à chaque fois.Click Test until the counter reaches 5 closing the message boxes each time.
Le réinitialiser bouton s’affiche à nouveau.The Reset button re-appears.
Cliquez sur Réinitialiser.Click Reset.
Le compteur est remis à 0.The counter resets to 0.
Étapes suivantesNext Steps
Quand vous générez un contrôle de boîte à outils , Visual Studio crée un fichier nommé nom_projet.vsix dans le dossier \bin\debug\ de votre projet.When you build a Toolbox control, Visual Studio creates a file named ProjectName.vsix in the \bin\debug\ folder of your project. Vous pouvez déployer le contrôle en chargeant le fichier .vsix sur un réseau ou un site web.You can deploy the control by uploading the .vsix file to a network or to a Web site. Lorsqu’un utilisateur ouvre le fichier .vsix, le contrôle est installé et ajouté à Visual Studio boîte à outils sur l’ordinateur de l’utilisateur.When a user opens the .vsix file, the control is installed and added to the Visual Studio Toolbox on the user's computer. Ou bien, vous pouvez télécharger le fichier .vsix sur le galerie Visual Studio de site Web afin que les utilisateurs puissent le trouver en naviguant dans le outils / extensions et mises à jour boîte de dialogue.Alternatively, you can upload the .vsix file to the Visual Studio Gallery Web site so that users can find it by browsing in the Tools / Extension and Updates dialog.
Voir aussiSee Also
Extension d’autres parties de Visual Studio Extending other parts of Visual Studio
Création d’un contrôle de boîte à outils WPF Creating a WPF Toolbox Control
Extension d’autres parties de Visual Studio Extending Other Parts of Visual Studio
Concepts de base du développement de contrôles Windows FormsWindows Forms Control Development Basics