Here is modified version with renamed variables of Inventor application for better understanding.
If you pass the inventor using constructor you don't need to use them static.
class StandardAddInServer : ApplicationAddInServer
{
Inventor.Application inventorAtAddInLevel;
MyCommand myCommand;
public void Activate(ApplicationAddInSite AddInSiteObject, bool FirstTime)
{
//Get inventor app instance
inventorAtAddInLevel = AddInSiteObject.Application;
//Pass the inventor app to the command class
myCommand = new MyCommand(inventorAtAddInLevel);
//Create buttons in ribbon
inventorAtAddInLevel.UserInterfaceManager
.Ribbons["ZeroDoc"]
.RibbonTabs["id_TabTools"]
.RibbonPanels["id_PanelP_ToolsOptions"]
.CommandControls.AddButton(myCommand.ButtonDefinition);
inventorAtAddInLevel.UserInterfaceManager
.Ribbons["Part"]
.RibbonTabs["id_TabModel"]
.RibbonPanels["id_PanelP_Model2DSketchCreate"]
.CommandControls.AddButton(myCommand.ButtonDefinition);
}
public void Deactivate()
{
//Clear all buttons from ribbon
var myCommandButtonAsControlDef = myCommand.ButtonDefinition as ControlDefinition;
var myCommandControls =
inventorAtAddInLevel.UserInterfaceManager.AllReferencedControls(myCommandButtonAsControlDef);
foreach (CommandControl cmdCtrl in myCommandControls)
{
try { cmdCtrl.Delete(); }
catch { /* IGNORE ALL ERRORS*/ }
}
//Clear button definition
myCommand.ButtonDefinition.Delete();
//Finalize the addin
inventorAtAddInLevel = null;
}
// Obsolete
public void ExecuteCommand(int CommandID) { }
// Not implemented
public object Automation => null;
}
class MyCommand
{
private readonly Inventor.Application inventorAtMyCommandLevel;
private ButtonDefinition buttonDef;
public ButtonDefinition ButtonDefinition => buttonDef;
public MyCommand(Inventor.Application inventorAsArgument)
{
inventorAtMyCommandLevel = inventorAsArgument;
buttonDef = inventorAtMyCommandLevel.CommandManager.ControlDefinitions.AddButtonDefinition(
"My command", "MyCommandInternalName", CommandTypesEnum.kQueryOnlyCmdType /* etc. */);
buttonDef.OnExecute += MyCommand_OnExecute;
}
private void MyCommand_OnExecute(NameValueMap Context)
{
MessageBox.Show(inventorAtMyCommandLevel.ActiveDocument.DisplayName, "My command");
}
}