Search code examples
vstoexcel-addinsribbon-control

Cannot enable a Ribbon button programmatically


I developed a VSTO 4 add-in for Excel. It works perfect, however, I have a button placed in the custom tab of its Ribbon control that is initially disabled.

After clicked other ribbon button in my custom tab, I need to enable the initially disabled button.

I tried with:

btnCancelar.Visible = true;

In the Click event of a button, but button is not shown. The strange thing is that when debugging, it still does not appear, but if a MessageBox is shown, the button get visible at last.

I don't understand this behaviour. How can I enable or disable a ribbon button dynamically by code?


Solution

  • I have created a workaround to this.

    It was simple. Just started the long running process in different thread. That way, cancel button is shown when it should and then hidden after the process ends.

    I used this code to launch the process in the Ribbon.cs code:

    btnCancelar.Visible = true;
    
    Action action = () => {
                               Formatter.GenerateNewSheet(Formatter.TargetType.ImpresionEtiquetas, frm.CustomerID, workbook, btnCancelar);
                          };
    System.Threading.Tasks.Task.Factory.StartNew(action);
    

    And inside the process method I have this code:

        public static bool GenerateNewSheet(TargetType type, string customerID, Excel.Workbook workbook, Microsoft.Office.Tools.Ribbon.RibbonButton btnCancelar)
        {
            try
            {
                _cancelled = false;
                InfoLog.ClearLog();
    
                switch (type)
                {
                    case TargetType.ImpresionEtiquetas:
                        return GenerateTagPrinting(customerID, workbook);
                }
    
                return false;
            }
            finally
            {
                btnCancelar.Visible = false;
            }
        }
    

    The interesting thing here I have discovered is that Excel is thread safe, so it was not necessary to add a synchronization mechanism neither when adding rows in the new sheet nor when setting Visible property to false again.

    Regards

    Jaime