如何使用ThisAddInclass的Workbook_Open中的C#代码访问Excel VSTO加载项中打开的窗体?

ulydmbyx  于 2023-06-07  发布在  C#
关注(0)|答案(1)|浏览(170)

'请知道在Workbook_Open of c# Excel ThisAddInclass中运行打开窗体的fmX的代码'

public partial class fmX : Form {
    public fmX() {
        InitializeComponent();
        xl.Application app = Globals.ThisAddIn.Application;            
        foreach (xl.Workbook wb in app.Workbooks) this.listBox1.Items.Add(wb.Name);
    }
}

public partial class ThisAddIn
{
    private void ThisAddIn_Startup(object sender, System.EventArgs e)
    {
        this.Application.WorkbookOpen += Workbook_Open;
    }

    private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
    {}

    private void Workbook_Open(xl.Workbook wb) {
        //this code ~~~
    }
    private void InternalStartup()
    {
        this.Startup += new System.EventHandler(ThisAddIn_Startup);
        this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);
    }
}

'我想知道//这段代码中的~~~'

tcomlyy6

tcomlyy61#

您可以按以下方式在外接程序类中声明fmX类的示例:

public partial class ThisAddIn
{
    private fmX formInstance;
    private void ThisAddIn_Startup(object sender, System.EventArgs e)
    {
        this.Application.WorkbookOpen += Workbook_Open;
    }

然后在Open事件中,您可以创建一个新示例并将其显示给用户:

private void Workbook_Open(xl.Workbook wb) {
     formInstance = new fmX();
     formInstance.Show();
    }

请注意,要避免对话框与其他窗口或对话框重叠的任何问题,您需要在调用Show方法时指定父窗口句柄。使用IWin32Window接口指定父窗口句柄。此接口在公开Win32 HWND句柄的对象(包括Office应用程序)上实现。

相关问题