首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Microsoft Office Interop超时

Microsoft Office Interop超时
EN

Stack Overflow用户
提问于 2013-07-04 18:23:14
回答 2查看 1.4K关注 0票数 2

我正在使用一个使用Microsoft Office Interop的C#程序,它允许您基本上通过编程使用Microsoft Word、Excel和PowerPoint。

我遇到的一个不幸的方面是,有时程序会弹出一个对话框,暂停代码。例如,如果代码突然不能保存在您期望能够保存的位置,这可能会发生,这意味着即使这个问题稍后得到修复,整个程序也可能会暂停。

在许多其他情况下,可能会引发额外的对话框。

因此,我的目的是为此实现某种超时机制,借此我可以杀死Interop实例,而不是将整个程序捆绑在一起。有没有人能建议一种方法呢?目前,它将互操作调用包装在System.Action中,并在给定时间后中止该线程,但我想知道是否有更好的方法。

EN

回答 2

Stack Overflow用户

发布于 2013-07-04 20:26:51

您可以通过实现OLE消息筛选器来完成此操作。有关更多详细信息,请参阅this answer

票数 1
EN

Stack Overflow用户

发布于 2013-07-23 12:07:14

许多人不建议终止该进程;请参阅How to properly clean up Excel interop objectsUnderstanding Garbage Collection in .net

下面是我用来终止我创建的Excel实例的代码。您将需要对其进行一些重构以满足您的需求。您将看到如何使用Excel提供的窗口句柄获取进程ID。我想对于Word或Powerpoint来说,这个过程应该是一样的。

代码语言:javascript
复制
'http://msdn.microsoft.com/en-us/library/ms633522%28v=vs.85%29.aspx
<System.Runtime.InteropServices.DllImport("user32.dll", SetLastError:=True)> _
    Private Shared Function GetWindowThreadProcessId(ByVal hWnd As IntPtr, _
    ByRef lpdwProcessId As Integer) As Integer
End Function

Sub Work()

    'declare process; will be used later to attach the Excel process
    Dim XLProc As Process

    'start the application using late binding
    Dim xlApp As Object = CreateObject("Excel.Application")

    'or use early binding
    'Dim xlApp As Microsoft.Office.Interop.Excel

    'get the window handle
    Dim xlHWND As Integer = xlApp.hwnd

    'this will have the process ID after call to GetWindowThreadProcessId
    Dim ProcIdXL As Integer = 0

    'get the process ID
    GetWindowThreadProcessId(xlHWND, ProcIdXL)

    'get the process
    XLProc = Process.GetProcessById(ProcIdXL)


    'do some work with Excel here using xlApp

    'be sure to save and close all workbooks when done

    'release all objects used (except xlApp) using NAR(x)


    'Quit Excel 
    xlApp.quit()

    'Release
    NAR(xlApp)

    'Do garbage collection to release the COM pointers
    'http://support.microsoft.com/kb/317109
    GC.Collect()
    GC.WaitForPendingFinalizers()

    'I prefer to have two parachutes when dealing with the Excel process
    'this is the last answer if garbage collection were to fail
    If Not XLProc Is Nothing AndAlso Not XLProc.HasExited Then
        XLProc.Kill()
    End If
End Sub

Private Sub NAR(ByVal o As Object)
    'http://support.microsoft.com/kb/317109
    Try
        While (System.Runtime.InteropServices.Marshal.ReleaseComObject(o) > 0)
        End While
    Catch
    Finally
        o = Nothing
    End Try
End Sub
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17467843

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档