Tired of the strange case of sporadic COMException 0x800A01A8 calling CommandBarButton.Delete from a Visual Studio add-in, but very annoying, I decided to take a closer look and solve it. First, I noticed that my MZ-Tools add-in only calls CommandBarButton.Delete for buttons that places on VS built-in toolbars. For buttons that places on its own toolbar, I don’t call CommandBarButton.Delete since I will destroy the toolbar anyway and that will remove its buttons (which is also faster). So, if your add-in doesn’t add buttons to built-in toolbars of VS chances are that you’ll never experience this COMException. Alas, my add-in adds buttons to VS built-in toolbars that must be removed. For these, I took the following approach:
- Rather than calling CommandBarButton.Delete when the add-in is unloaded, and I remove the command calling Command.Delete (which also automatically deletes all CommandBarButtons created from that command) and I create it again.
- As you may know, in general add-ins should not delete commands when unloaded because:
- Command keyboard bindings are lost. To solve this, before deleting the command I get the command keyboard bindings (Command.Bindings) and I restore them when re-creating the command.
- If the user has created a button from that command on some other toolbar of her choice (see “Addition of a button of the add-in to a toolbar not belonging to it” case in my article HOWTO: Handling buttons and toolbars user customizations from a Visual Studio add-in), that button will be lost when the add-in is unloaded. There is no solution to this case, but I can live with that. Hopefully my users don’t need to create buttons from my add-in on other toolbars (I strive for providing good button/toolbar customization inside the add-in).