Laurent Kempé
Créer une CommandBar sous Word 2003
Cette astuce vous montre comment créer une CommandBar avec des buttons sous Word 2003 à l'aide de VSTO
Par Laurent Kempé publié le 16/01/2005 à 14:07, lu 9996 fois,
Pour commencer nous devons déclarer une variable de type CommandBar et une autre de type CommandBarButton qui sera ajoutée à la CommandBar :
private CommandBar oCommandBarWrite = null;
private CommandBarButton oButtonNew = null;
Lorsqu'un document est ouvert nous pouvons rajouter la CommandBar à Word 2003 :
/// <summary>
/// Called when the document is opened.
/// </summary>
protected void ThisDocument_Open()
{
    setupCommandBars();

        ...

}
Nous centralisons la création de toutes les CommandBar que nous voulons ajouter dans une méthode. Cette méthode déclare que nous voulons customiser notre document et appel une méthode par CommandBar que nous voulons créer :
private void setupCommandBars()
{
    ThisApplication.CustomizationContext = ThisDocument;

    setupWriteCommandBar();
}
Nous créons une nouvelle CommandBar en utilisant l'objet TheApplication mis à notre disposition par le template de VSTO. Puis nous lui ajoutons des boutons et la rendons visible :
private void setupWriteCommandBar()
{
    oCommandBarWrite = ThisApplication.CommandBars.Add("Tech Head Brothers - Write", oMissing, oMissing, true);

    this.AddButton(ref oCommandBarWrite,
                   ref oButtonNew,
                   new _CommandBarButtonEvents_ClickEventHandler(oButtonNew_Click),
                   "New Document",
                   12);
    ...

    oCommandBarWrite.Visible = true;
}
Cette méthode nous permet de généraliser au sein d'une seule méthode l'ajout d'un bouton à une CommandBar :
private void AddButton(ref CommandBar oCommandBar, 
                       ref CommandBarButton oButton, 
                       _CommandBarButtonEvents_ClickEventHandler handler, 
                       string caption, 
                       int faceid)
{
    // Add a button to the command bar.
    oButton = (CommandBarButton) oCommandBar.Controls.Add(MsoControlType.msoControlButton, 
                                                          oMissing,
                                                          oMissing,
                                                          oMissing);
    // Set the caption and face ID.
    oButton.Caption = caption;
    oButton.FaceId = faceid;

    // Set up a delegate for the Click event.
    oButton.Click += handler;
}
Et voilà enfin comment récupérer l'événement click sur le bouton :
private void oButtonNew_Click(CommandBarButton Ctrl, ref bool Cancel)
{
...
}
 
» Démarrer une discussion