Thursday, April 23, 2009

Word CommandBarButton Tag

I'm guessing that no one cares about this, but I just spent all day tracking down this issue and blogging about it is going to make me feel better.

I was adding buttons to the toolbar in Word through Visual Studio Tools for Office (VSTO). My situation had me adding buttons to certain open documents. I ran into a problem where after adding two (or more) buttons to two (or more) documents I started getting two click (or more) click events every time I clicked (just once!) on any of the buttons.

CommandBar cmdBar; // get this from somewhere
CommandBarButton cmdBarBtn = (CommandBarButton)cmdBar.Controls.Add( blah, blah, blah );
cmdBarBtn.Caption = "Example";
cmdBarBtn.Tag = "Example";
cmdBarBtn.Click += btn_Click;

Turns out, that Tag property is really really special. You expect the CommandBarButton object to pretty much take care of differentiating one button from another, but that's not how it works in Word.

Word uses the Tag to differentiate between all the various button instances. Even though executing the code above twice DEFINITELY creates two different button instances (I verified by changing the Caption on the second one), Word can't tell them apart because they have the same Tag. So, because you registered two click events on the same Tag, you get two click events to fire.

I changed my code to:
cmdBarBtn.Tag = Guid.NewGuid().ToString();

Now my clicks are properly associated with the button that was clicked.

Ahh... I do feel better.

4 comments:

  1. Thanks for this post. It seems that this behavior is true for CommandBarButton objects in general. I just ran into the very same problem in Outlook!

    ReplyDelete
  2. Kevin,

    Sometimes you never know how your blog would might end up helping someone real quick. So Thanks for this.

    ReplyDelete
  3. Thanks..
    This helps me alot :)

    ReplyDelete
  4. Thanks. That helped! I've thought that I'm an idiot. It's really strange.
    Btw: it is somehow documented on MSDN in help for Tag property of CommandBarButton:
    http://msdn.microsoft.com/en-us/library/aa432923%28office.12%29.aspx

    Hlina P.

    ReplyDelete

Note: Only a member of this blog may post a comment.