Complément MS Word: Gestionnaire de clic droit

Je développe un complément pour MS Word 2010 et je souhaite append quelques éléments de menu au menu contextuel (uniquement lorsque du texte est sélectionné). J’ai vu quelques exemples d’append des éléments, mais je n’ai pas trouvé comment append des éléments de manière conditionnelle. En bref, je veux remplacer quelque chose comme le gestionnaire OnRightClick. Merci d’avance.

C’est assez simple, vous devez gérer l’événement WindowBeforeRightClick . Dans l’événement, localisez la barre de commande requirejse et le contrôle specfic, puis gérez la propriété Visible ou Enabled .

Dans l’exemple ci-dessous, je bascule la propriété Visible d’un bouton personnalisé créé dans la barre de commandes de texte en fonction de la sélection (si la sélection contient “C #”, masque le bouton, sinon affiche-le)

  //using Word = Microsoft.Office.Interop.Word; //using Office = Microsoft.Office.Core; Word.Application application; private void ThisAddIn_Startup(object sender, System.EventArgs e) { application = this.Application; application.WindowBeforeRightClick += new Word.ApplicationEvents4_WindowBeforeRightClickEventHandler(application_WindowBeforeRightClick); application.CustomizationContext = application.ActiveDocument; Office.CommandBar commandBar = application.CommandBars["Text"]; Office.CommandBarButton button = (Office.CommandBarButton)commandBar.Controls.Add( Office.MsoControlType.msoControlButton); button.accName = "My Custom Button"; button.Caption = "My Custom Button"; } public void application_WindowBeforeRightClick(Word.Selection selection, ref bool Cancel) { if (selection != null && !Ssortingng.IsNullOrEmpty(selection.Text)) { ssortingng selectionText = selection.Text; if (selectionText.Contains("C#")) SetCommandVisibility("My Custom Button", false); else SetCommandVisibility("My Custom Button", true); } } private void SetCommandVisibility(ssortingng name, bool visible) { application.CustomizationContext = application.ActiveDocument; Office.CommandBar commandBar = application.CommandBars["Text"]; commandBar.Controls[name].Visible = visible; }