gpt4 book ai didi

c# - 保留 excel 句柄时崩溃

转载 作者:太空宇宙 更新时间:2023-11-03 13:47:49 24 4
gpt4 key购买 nike

启动 Excel 加载项时,我使用以下代码保留 Excel 窗口的句柄:

ExcelWindow = new NativeWindow();
ExcelWindow.AssignHandle(new IntPtr(Application.Hwnd));

说到释放句柄,我尽量在关机的​​时候做:

private void ThisAddInShutdown(object sender, EventArgs e)
{
try
{
ExcelWindow.ReleaseHandle();
}
catch
{

}
}

在 Debug模式下退出 excel 时,一切正常。不幸的是,当在生产系统上运行这段代码时,我遇到了崩溃,无法调试正在发生的事情。我收到一个“Windows 正在检查此问题”窗口,随后它消失了,仅此而已。

这真的没什么大不了的,但我不想用这样的事情来烦扰用户。那么,有没有人知道它可能是什么以及我如何调试它?谢谢。

最佳答案

我的解决方案:

public partial class ThisAddIn
{
ExcelWindow window;

private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
window = new ExcelWindow();

Application.WorkbookBeforeClose += new Excel.AppEvents_WorkbookBeforeCloseEventHandler(Application_WorkbookBeforeClose);
Application.WorkbookActivate += new Excel.AppEvents_WorkbookActivateEventHandler(Application_WorkbookActivate);
Application.WorkbookDeactivate += new Excel.AppEvents_WorkbookDeactivateEventHandler(Application_WorkbookDeactivate);
}

void Application_WorkbookDeactivate(Excel.Workbook Wb)
{
window.ReleaseHandle();
}

void Application_WorkbookActivate(Excel.Workbook Wb)
{
window.AssignHandle(new IntPtr(Application.Hwnd));
}

void Application_WorkbookBeforeClose(Excel.Workbook Wb, ref bool Cancel)
{
if (Application.Workbooks.Count > 1 || window.Handle == IntPtr.Zero) return;
Cancel = true;
window.ReleaseHandle();
Dispatcher.CurrentDispatcher.BeginInvoke(new MethodInvoker(Application.Quit), null);
}

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

#region VSTO generated code

/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InternalStartup()
{
this.Startup += new System.EventHandler(ThisAddIn_Startup);
this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);
}

#endregion
}

关于c# - 保留 excel 句柄时崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14673104/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com