我正在开发一个excel添加。当我的功能区加载时,我添加一个单元格上下文菜单,其中包含一个按钮。我将处理程序附加到按钮的单击事件以选择文件。当我运行excel时,它可以正常使用默认的第一张表。但是,如果我打开一个新工作表,单击时没有任何反应。为什么呢?
我的功能区加载功能:
private void Ribbon1_Load(object sender, RibbonUIEventArgs e)
{
Helper.SetVar(Globals.ThisAddIn.Application, Globals.Factory);
}
我有几个添加引用工具箱DLL。所以这是工具箱DLL的公共静态Helper类中的setVar函数:
public static void SetVar(Excel.Application appSource, Microsoft.Office.Tools.Excel.ApplicationFactory FactorySource)
{
if(path=="")
{
string fullPath = typeof(Helper).Assembly.CodeBase;
string theDirectory = Path.GetDirectoryName(fullPath);
path = new Uri(theDirectory).LocalPath;
}
if (app == null)
app = appSource;
if (Factory == null)
Factory = FactorySource;
rightClickMenu();
}
它调用rightClickMenu,即:
public static void rightClickMenu()
{
bool val = false;
removeRightClickMenu(ref val);
Office.CommandBarPopup ctrl = (Office.CommandBarPopup)app.CommandBars["Cell"].Controls.Add(Type: Office.MsoControlType.msoControlPopup, Before: 1);
ctrl.Caption = "Perso";
Office.CommandBarButton btn = (Office.CommandBarButton)ctrl.Controls.Add(Type: Office.MsoControlType.msoControlButton);
btn.Caption = "Sélectionner un fichier";
btn.Click += new Office._CommandBarButtonEvents_ClickEventHandler(selectFile);
}
点击处理程序是:
public static void selectFile(Office.CommandBarButton ctrl, ref bool Cancel)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = "c:\\";
openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
var filename = openFileDialog1.FileName;
//var filename = openFileDialog1.SafeFileName;
app.ActiveCell.Value = filename;
}
}