我的上下文菜单按钮只触发一次。btn对象在启动时死亡。我怎么才能修好它?
怎么才能这么早地修复调用对象呢?
public partial class ThisAddIn
{
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
PicPaste btn = new PicPaste(this.Application);}class PicPaste
{
private Excel.Application application;
private Office.CommandBarButton picpasteMenuItem;
public PicPaste(Excel.Application app)
{
application = app;
CreatePicpasteBtn();
}
public void CreatePicpasteBtn()
{
Office.MsoControlType contextMenuItem = Office.MsoControlType.msoControlButton;
Office.CommandBar commandBarCell = application.CommandBars["Cell"];
picpasteMenuItem = commandBarCell.Controls.Add(contextMenuItem, Type.Missing, Type.Missing, 5, true)
as Office.CommandBarButton;
if (picpasteMenuItem != null)
{
picpasteMenuItem.Style = Office.MsoButtonStyle.msoButtonCaption;
picpasteMenuItem.Caption = "Вставить изображение в коммент";
picpasteMenuItem.Click += new Office._CommandBarButtonEvents_ClickEventHandler(
PicPasteMenuItemClick);
}
}
private static void PicPasteMenuItemClick(Office.CommandBarButton Ctrl, ref bool CancelDefault)
{
...some code here
}
}发布于 2016-05-23 17:35:53
问题是在方法/事件中声明和实例化对象PicPaste btn = new PicPaste(this.Application);。这意味着它的作用域将被限定为此过程;当该过程结束时,它将超出范围,并最终将被垃圾收集。
在任何过程之外,您需要在类级别声明任何应该存在于外接程序生命周期内的对象。然后他们会在范围内直到你的外接程序卸载。
因此,例如:
public partial class ThisAddIn
{
PicPaste btn = null;
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
btn = new PicPaste(this.Application);
}发布于 2016-05-23 18:37:23
看起来PicPaste实例的范围在某种程度上是有限的。但是这种方法是正确的--将源对象定义在类级别,以防止GC从堆中滑动。尝试使用将存储在外接程序类级别的控件列表,或者类似的内容:
PicPaste btn = null;
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
btn = new PicPaste(this.Application);
}https://stackoverflow.com/questions/37392956
复制相似问题