none
Outlook add-in 程序创建的菜单只能有效点击一次 RRS feed

  • 问题

  • 我写了一个Add-in程序在outlook上添加Menu,但是只能点击一次,请帮忙解决一下,谢谢

     

        private void ThisAddIn_Startup(object sender, System.EventArgs e)
        {
          initMenuBar();
        }
    
        private void initMenuBar()
        {
          Office.CommandBar menuBar = Application.ActiveExplorer().CommandBars.ActiveMenuBar;
          Office.CommandBarPopup newMenuBar;
          Office.CommandBarButton buttonOne;
    
          newMenuBar = (Office.CommandBarPopup)menuBar.Controls.Add(Office.MsoControlType.msoControlPopup, missing, missing, missing, true);
    
          if (newMenuBar != null)
          {
            newMenuBar.Caption = "&MenuBar";
    
            buttonOne = (Office.CommandBarButton)newMenuBar.Controls.Add(Office.MsoControlType.msoControlButton, missing, missing, 1, false);
            buttonOne.Style = Office.MsoButtonStyle.msoButtonIconAndCaption;
            buttonOne.Caption = "button1";
            buttonOne.Click += new Office._CommandBarButtonEvents_ClickEventHandler(btnConfirm_Click);
    
            newMenuBar.Visible = true;
          }
        }
    
        private void btnConfirm_Click(Office.CommandBarButton btn, ref bool cancel)
        {
           MessageBox.Show("Some code");
        }
    
    2010年6月10日 2:54

全部回复

  • 挥泪继续自己顶

    2010年6月21日 1:50
  • Your button object is going out of scope and is being garbage collected,
    therefore it won't fire again on a click.

    That's a very common problem in managed code if you don't declare your
    objects at the correct scope level.

    Declare your button object at the class level and not within Startup(). Then
    in Startup() you instantiate the object, it will remain alive until you
    release it explicitly.

    从英文论坛找到的,好像是托管代码中常出现的问题。因为声明按钮变量的位置在initMenuBar内,后来被GC干掉就不起作用了。

    所以我把声明移到 ThisAddIn_Startup 的外面一层(class 级)就没问题了,我自己有点无语了。

    2010年6月21日 6:32