我想在Excel的上下文菜单(右键单击)上打开一个新窗口。
为此,我打开了一个Excel文件,并在右键单击时添加了Go to Link
菜单,但是当我单击此菜单时,它不会打开一个窗口并显示错误消息"STA thread attribute must be defined"
。
以下是代码。
Excel.Application _Excel = new Excel.Application();
Excel.Worksheet WS = new Excel.Worksheet();
Excel.Workbook WB;
Object defaultArg = Type.Missing;
try
{
_Excel.Visible = true;
CommandBar cellbar = _Excel.CommandBars["Cell"];
CommandBarButton button =(CommandBarButton)cellbar.FindControl(MsoControlType.msoControlButton, 0, "MYRIGHTCLICKMENU", Missing.Value, Missing.Value);
if (button == null)
{
// add the button
button = (CommandBarButton)cellbar.Controls.Add(MsoControlType.msoControlButton, Missing.Value, Missing.Value, cellbar.Controls.Count, true);
button.Caption = "Go to Link";
button.BeginGroup = true;
button.Tag = "MYRIGHTCLICKMENU";
button.Click += new _CommandBarButtonEvents_ClickEventHandler(MyButton_Click);
}
WB = _Excel.Workbooks.Open(pathToFile, defaultArg, defaultArg, defaultArg, defaultArg,
defaultArg, defaultArg, defaultArg, defaultArg,
defaultArg, defaultArg, defaultArg, defaultArg,
defaultArg, defaultArg);
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(WB);
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(_Excel);
}
catch (Exception ex)
{
// WB.Close(false, Type.Missing, Type.Missing);
throw;
}
private void MyButton_Click(CommandBarButton cmdBarbutton, ref bool cancel)
{
Window m = new Window();
m.showDialog();
}
任何建议都会有很大的帮助。